summaryrefslogtreecommitdiffstats
path: root/public/manual/en
diff options
context:
space:
mode:
Diffstat (limited to 'public/manual/en')
0 files changed, 0 insertions, 0 deletions
='#n8'>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 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036
/*
 * Copyright 2011, The gwtquery team.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.query.client;

import static com.google.gwt.query.client.GQuery.$;
import static com.google.gwt.query.client.GQuery.document;
import static com.google.gwt.query.client.plugins.QueuePlugin.Queue;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayMixed;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.core.client.ScriptInjector;
import com.google.gwt.dom.client.BodyElement;
import com.google.gwt.dom.client.ButtonElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.OptionElement;
import com.google.gwt.dom.client.SelectElement;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.TextAreaElement;
import com.google.gwt.query.client.css.HasCssValue;
import com.google.gwt.query.client.css.TakesCssValue;
import com.google.gwt.query.client.css.TakesCssValue.CssSetter;
import com.google.gwt.query.client.impl.AttributeImpl;
import com.google.gwt.query.client.impl.DocumentStyleImpl;
import com.google.gwt.query.client.impl.SelectorEngine;
import com.google.gwt.query.client.js.JsCache;
import com.google.gwt.query.client.js.JsMap;
import com.google.gwt.query.client.js.JsNamedArray;
import com.google.gwt.query.client.js.JsNodeArray;
import com.google.gwt.query.client.js.JsObjectArray;
import com.google.gwt.query.client.js.JsUtils;
import com.google.gwt.query.client.plugins.Effects;
import com.google.gwt.query.client.plugins.Events;
import com.google.gwt.query.client.plugins.Plugin;
import com.google.gwt.query.client.plugins.Widgets;
import com.google.gwt.query.client.plugins.ajax.Ajax;
import com.google.gwt.query.client.plugins.ajax.Ajax.Settings;
import com.google.gwt.query.client.plugins.deferred.Deferred;
import com.google.gwt.query.client.plugins.deferred.PromiseFunction;
import com.google.gwt.query.client.plugins.effects.PropertiesAnimation.Easing;
import com.google.gwt.query.client.plugins.events.EventsListener;
import com.google.gwt.query.client.plugins.widgets.WidgetsUtils;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.EventListener;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * GwtQuery is a GWT clone of the popular jQuery library.
 */
public class GQuery implements Lazy<GQuery, LazyGQuery> {

  private enum DomMan {
    AFTER, APPEND, BEFORE, PREPEND;
  }

  /**
   * A POJO used to store the top/left CSS positioning values of an element.
   */
  public static class Offset {
    public int left;
    public int top;

    public Offset(int left, int top) {
      this.left = left;
      this.top = top;
    }

    public Offset add(int left, int top) {
      return new Offset(this.left + left, this.top + top);
    }

    public String toString() {
      return top + "+" + left;
    }
  }

  /**
   * Class used internally to create DOM element from html snippet.
   */
  private static class TagWrapper {
    public static final TagWrapper DEFAULT = new TagWrapper(0, "", "");
    private String postWrap;
    private String preWrap;
    private int wrapDepth;

    public TagWrapper(int wrapDepth, String preWrap, String postWrap) {
      this.wrapDepth = wrapDepth;
      this.postWrap = postWrap;
      this.preWrap = preWrap;
    }
  }

  /**
   * Implementation class to modify attributes.
   */
  protected static AttributeImpl attributeImpl;

  /**
   * The body element in the current page.
   */
  public static final BodyElement body = GWT.isClient() ? Document.get().getBody() : null;

  /**
   * A Browser object with a set of browser-specific flags.
   */
  public static final Browser browser = GWT.isClient() ? GWT.<Browser>create(Browser.class) : null;

  /**
   * An object with the same methods than window.console.
   */
  public static final Console console = GWT.isClient() ? GWT.<Console>create(Console.class) : null;

  /**
   * Object to store element data (public so as we can access to it from tests).
   */
  public static JsCache dataCache = null;

  /**
   * The document element in the current page.
   */
  public static final Document document = GWT.isClient() ? Document.get() : null;

  /**
   * Static reference Effects plugin.
   */
  public static Class<Effects> Effects = com.google.gwt.query.client.plugins.Effects.Effects;

  /**
   * Implementation engine used for CSS selectors.
   */
  protected static SelectorEngine engine;

  /**
   * Static reference Events plugin.
   */
  public static Class<Events> Events = com.google.gwt.query.client.plugins.Events.Events;

  /**
   * A static reference to the GQuery class.
   */
  public static Class<GQuery> GQUERY = GQuery.class;

  private static final String OLD_DATA_PREFIX = "old-";

  private static final String OLD_DISPLAY = OLD_DATA_PREFIX + "display";

  private static JsMap<Class<? extends GQuery>, Plugin<? extends GQuery>> plugins;

  // Sizzle POS regex : usefull in some methods
  // TODO: Share this static with SelectorEngineSizzle
  private static RegExp posRegex = RegExp
      .compile("^:(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\))?(?=[^\\-]|$)$");

  /**
   * Implementation class used for style manipulations.
   */
  private static DocumentStyleImpl styleImpl;

  private static RegExp tagNameRegex = RegExp.compile("<([\\w:-]+)");

  /**
   * Static reference to the Widgets plugin.
   */
  public static Class<Widgets> Widgets = com.google.gwt.query.client.plugins.Widgets.Widgets;

  /**
   * The window object.
   */
  public static final Element window = GWT.isClient() ? ScriptInjector.TOP_WINDOW.<Element> cast()
      : null;

  private static Element windowData = null;

  private static JsNamedArray<TagWrapper> wrapperMap;

  /**
   * Create an empty GQuery object.
   */
  public static GQuery $() {
    return new GQuery(JsNodeArray.create());
  }

  /**
   * Wrap a GQuery around an existing element.
   */
  public static GQuery $(Element element) {
    return new GQuery(element);
  }

  /**
   * Wrap a GQuery around an event's target element.
   */
  public static GQuery $(Event event) {
    return event == null ? $() : $((Element) event.getCurrentEventTarget().cast());
  }

  /**
   * Wrap a GQuery around the element of a Function callback.
   */
  public static GQuery $(Function f) {
    return $(f.getElement());
  }

  /**
   * Wrap a GQuery around an existing javascript element, event, node, nodelist, function or array.
   */
  public static GQuery $(JavaScriptObject jso) {
    if (jso == null) {
      return $();
    }
    // Execute a native javascript function like jquery does
    if (JsUtils.isFunction(jso)) {
      new JsUtils.JsFunction(jso).fe();
      return $();
    }
    // Wraps a native array like jquery does
    if (!JsUtils.isWindow(jso) && !JsUtils.isElement(jso) && JsUtils.isArray(jso)) {
      JsArrayMixed c = jso.cast();
      JsNodeArray elms = JsNodeArray.create();
      for (int i = 0; i < c.length(); i++) {
        Object obj = c.getObject(i);
        if (obj instanceof Node) {
          elms.addNode((Node) obj);
        }
      }
      return $(elms);
    }

    return JsUtils.isWindow(jso) ? $(jso.<Element> cast()) :
        JsUtils.isElement(jso) ? $(jso.<Element> cast()) :
            JsUtils.isEvent(jso) ? $(jso.<Event> cast()) :
                JsUtils.isNodeList(jso) ? $(jso.<NodeList<Element>> cast()) :
                    $(jso.<Element> cast());
  }

  /**
   * Wrap a GQuery around any object, supported objects are:
   *   String, GQuery, Function, Widget, JavaScriptObject.
   *
   * In the case of string, we accept a CSS selector which is then used to match a set of
   * elements, or a raw HTML to create a GQuery element containing those elements. Xpath
   * selector is supported in browsers with native xpath engine.
   *
   * In the case of a JavaScriptObject we handle:
   *   Element, Event, Node, Nodelist and native functions or arrays.
   *
   * If the case of a native function, we execute it and return empty.
   */
  public static GQuery $(Object o) {
    if (o != null) {
      if (o instanceof String) {
        return $((String) o);
      }
      if (o instanceof GQuery) {
        return (GQuery) o;
      }
      if (o instanceof Function) {
        return $((Function) o);
      }
      if (JsUtils.isElement(o)) {
        return $(JsUtils.<Element> cast(o));
      }
      if (o instanceof JavaScriptObject) {
        return $((JavaScriptObject) o);
      }
      if (o instanceof IsWidget) {
        return $(Arrays.asList(o));
      }
      console
          .log("Error: GQuery.$(Object o) could not wrap the type : ", o.getClass().getName(), o);
    }
    return $();
  }

  /**
   * Create a new GQuery given a list of {@link com.google.gwt.dom.client.Node} or
   * {@link com.google.gwt.user.client.ui.IsWidget}.
   */
  public static GQuery $(List<?> nodesOrWidgets) {
    JsNodeArray elms = JsNodeArray.create();
    if (nodesOrWidgets != null) {
      for (Object o : nodesOrWidgets) {
        if (o instanceof Node) {
          elms.addNode((Node) o);
        } else if (o instanceof IsWidget) {
          elms.addNode(((IsWidget) o).asWidget().getElement());
        }
      }
    }
    return new GQuery(elms);
  }

  /**
   * Wrap a GQuery around an existing node.
   */
  public static GQuery $(Node n) {
    return $((Element) n);
  }

  /**
   * Wrap a GQuery around existing Elements.
   */
  public static GQuery $(NodeList<Element> elms) {
    return new GQuery(elms);
  }

  /**
   * This function accepts a string containing a CSS selector which is then used to match a set of
   * elements, or it accepts raw HTML creating a GQuery element containing those elements. Xpath
   * selector is supported in browsers with native xpath engine.
   */
  public static GQuery $(String selectorOrHtml) {
    return $(selectorOrHtml, document);
  }

  /**
   * This function accepts a string containing a CSS selector which is then used to match a set of
   * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
   * second parameter is is a class reference to a plugin to be used.
   *
   * Xpath selector is supported in browsers with native xpath engine.
   */
  public static <T extends GQuery> T $(String selector, Class<T> plugin) {
    return $(selector, document, plugin);
  }

  /**
   * This function accepts a string containing a CSS selector which is then used to match a set of
   * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
   * second parameter is the context to use for the selector, or the document where the new elements
   * will be created.
   *
   * Xpath selector is supported in browsers with native xpath engine.
   */
  public static GQuery $(String selectorOrHtml, Node ctx) {
    String selector = null;
    if (selectorOrHtml == null || (selector = selectorOrHtml.trim()).length() == 0) {
      return $();
    }
    if (selector.startsWith("<")) {
      return innerHtml(selectorOrHtml, JsUtils.getOwnerDocument(ctx));
    }
    return new GQuery().select(selectorOrHtml, ctx);
  }

  /**
   * This function accepts a string containing a CSS selector which is then used to match a set of
   * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
   * second parameter is the context to use for the selector. The third parameter is the class
   * plugin to use.
   *
   * Xpath selector is supported in browsers with native xpath engine.
   */
  @SuppressWarnings("unchecked")
  public static <T extends GQuery> T $(String selector, Node context, Class<T> plugin) {
    try {
      if (plugins != null) {
        T gquery = (T) plugins.get(plugin).init(new GQuery().select(selector, context));
        return gquery;
      }
      throw new RuntimeException("No plugin for class " + plugin);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * This function accepts a string containing a CSS selector which is then used to match a set of
   * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
   * second parameter is the context to use for the selector, or the document where the new elements
   * will be created.
   *
   * Xpath selector is supported in browsers with native xpath engine.
   */
  public static GQuery $(String selectorOrHtml, Widget context) {
    return $(selectorOrHtml, context.getElement());
  }

  /**
   * This function accepts a string containing a CSS selector which is then used to match a set of
   * elements, or it accepts raw HTML creating a GQuery element containing those elements. The
   * second parameter is the context to use for the selector. The third parameter is the class
   * plugin to use.
   *
   * Xpath selector is supported in browsers with native xpath engine.
   */
  public static <T extends GQuery> T $(String selector, Widget context, Class<T> plugin) {
    return $(selector, context.getElement(), plugin);
  }

  /**
   * Wrap a GQuery around one widget or an array of existing ones.
   */
  public static GQuery $(Widget... widgets) {
    return $(Arrays.asList(widgets));
  }

  /**
   * Wrap a GQuery around one node or an array of existing ones.
   */
  public static GQuery $(Node... nodes) {
    return $(Arrays.asList(nodes));
  }

  /**
   * Create an empty JSON object.
   */
  public static Properties $$() {
    return $$(null);
  }

  /**
   * Wrap a JSON object.
   */
  public static Properties $$(String properties) {
    return Properties.create(properties);
  }

  /**
   * Perform an ajax request to the server.
   */
  public static Promise ajax(Properties p) {
    return Ajax.ajax(p);
  }

  /**
   * Perform an ajax request to the server.
   */
  public static Promise ajax(Settings settings) {
    return Ajax.ajax(settings);
  }

  /**
   * Perform an ajax request to the server.
   */
  public static Promise ajax(String url, Settings settings) {
    return Ajax.ajax(url, settings);
  }

  protected static GQuery cleanHtmlString(String elem, Document doc) {
    MatchResult mResult = tagNameRegex.exec(elem);
    if (mResult == null) {
      return $(doc.createTextNode(elem));
    }
    String tag = mResult.getGroup(1);

    if (wrapperMap == null) {
      initWrapperMap();
    }

    TagWrapper wrapper = wrapperMap.get(tag.toLowerCase());

    if (wrapper == null) {
      wrapper = TagWrapper.DEFAULT;
    }

    // TODO: fix IE link tag serialization
    // TODO: fix IE <script> tag
    // TODO: add fixes for IE TBODY issue

    // We use a temporary element to wrap the elements
    Element div = doc.createDivElement();
    div.setInnerHTML(wrapper.preWrap + elem.trim() + wrapper.postWrap);
    Node n = div;
    int depth = wrapper.wrapDepth;
    while (depth-- != 0) {
      n = n.getLastChild();
    }

    return
    // return all nodes added to the wrapper
    $(n.getChildNodes())
        // detach nodes from their temporary parent
        .remove(null, false);
  }

  /**
   * Return true if the element b is contained in a.
   */
  public static boolean contains(Element a, Element b) {
    return getSelectorEngine().contains(a, b);
  }

  /**
   * Get the element data matching the key.
   */
  public static <T> T data(Element e, String key) {
    return data(e, key, null);
  }

  /**
   * Store arbitrary data associated with the specified element.
   *
   * We store this data in a global js object having the structure:
   *  datacache [element.hashCode()] [key] = value
   *
   * @return the value stored in the element with the given name
   */
  public static <T> T data(Element element, String key, T value) {
    return data(element, key, value, null);
  }

  private static <T> T data(Element element, String key, T value, Class<? extends T> clz) {
    if (dataCache == null) {
      windowData = JavaScriptObject.createObject().cast();
      dataCache = JavaScriptObject.createObject().cast();
    }
    element = element == window || element.getNodeName() == null ? windowData : element;
    if (element != null && key != null) {
      int id = element.hashCode();

      if (value == null) {
        return dataCache.exists(id) ? dataCache.getCache(id).get(key, clz) : null;
      }

      if (!dataCache.exists(id)) {
        dataCache.put(id, JsCache.createObject().cast());
      }
      dataCache.getCache(id).put(key, value);
    }
    return value;
  }

  /**
   * Execute a function around each object.
   */
  public static void each(JsArrayMixed objects, Function f) {
    for (int i = 0, l = objects.length(); i < l; i++) {
      f.f(i, objects.getObject(i));
    }
  }

  /**
   * Execute a function around each object.
   */
  public static <T> void each(List<T> objects, Function f) {
    for (int i = 0, l = objects.size(); i < l; i++) {
      f.f(i, objects.get(i));
    }
  }

  /**
   * Execute a function around each object.
   */
  public static <T> void each(T[] objects, Function f) {
    for (int i = 0, l = objects.length; i < l; i++) {
      f.f(i, objects[i]);
    }
  }

  /**
   * Perform an ajax request to the server using GET.
   */
  public static Promise get(String url, Properties data, final Function onSuccess) {
    return Ajax.get(url, data, onSuccess);
  }

  /**
   * We will use the fact as GWT use the widget itself as EventListener ! If no Widget associated
   * with the element, this method returns null.
   */
  protected static Widget getAssociatedWidget(Element e) {
    try {
      EventListener listener = DOM.getEventListener((com.google.gwt.user.client.Element) e);
      // No listener attached to the element, so no widget exist for this element
      if (listener == null) {
        return null;
      }
      if (listener instanceof Widget) {
        // GWT uses the widget as event listener
        return (Widget) listener;
      } else if (listener instanceof EventsListener) {
        // GQuery replaces the gwt event listener and save it
        EventsListener gQueryListener = (EventsListener) listener;
        if (gQueryListener.getOriginalEventListener() != null
            && gQueryListener.getOriginalEventListener() instanceof Widget) {
          return (Widget) gQueryListener.getOriginalEventListener();
        }
      }
    } catch (Exception e2) {
      // Some times this code could raise an exception.
      // We do not want GQuery to fail, but in dev-mode we log the error.
      e2.printStackTrace();
    }
    return null;
  }

  private static AttributeImpl getAttributeImpl() {
    if (attributeImpl == null) {
      attributeImpl = GWT.create(AttributeImpl.class);
    }
    return attributeImpl;
  }

  /**
   * Perform an ajax request to the server using POST and parsing the json response.
   */
  public static Promise getJSON(String url, Properties data, final Function onSuccess) {
    return Ajax.getJSON(url, data, onSuccess);
  }

  /**
   * Perform an ajax request to the server using scripts tags and parsing the json response. The
   * request is not subject to the same origin policy restrictions.
   *
   * Server side should accept a parameter to specify the callback funcion name, and it must return
   * a valid json object wrapped this callback function.
   *
   * Example:
   *
   * <pre>
    Client code:
    getJSONP("http://server.exampe.com/getData.php",$$("myCallback:'?', otherParameter='whatever'"),
      new Function(){ public void f() {
        Properties p = getDataProperties();
        alert(p.getStr("k1");
    }});

    Server response:
    myCallback({"k1":"v1", "k2":"v2"});
   </pre>
   *
   */
  public static Promise getJSONP(String url, Properties data, final Function onSuccess) {
    return Ajax.getJSONP(url, data, onSuccess);
  }

  protected static DocumentStyleImpl getStyleImpl() {
    if (styleImpl == null) {
      styleImpl = getSelectorEngine().getDocumentStyleImpl();
    }
    return styleImpl;
  }

  /**
   * Return only the set of objects with match the predicate.
   */
  @SuppressWarnings("unchecked")
  public static <T> T[] grep(T[] objects, Predicate f) {
    ArrayList<Object> ret = new ArrayList<Object>();
    for (int i = 0, l = objects.length; i < l; i++) {
      if (f.f(objects[i], i)) {
        ret.add(objects[i]);
      }
    }
    return (T[]) ret.toArray(new Object[0]);
  }

  private static boolean hasClass(Element e, String clz) {
    return e.getClassName().matches("(^|.*\\s)" + clz + "(\\s.*|$)");
  }

  private static void initWrapperMap() {

    TagWrapper tableWrapper = new TagWrapper(1, "<table>", "</table>");
    TagWrapper selectWrapper = new TagWrapper(1, "<select multiple=\"multiple\">", "</select>");
    TagWrapper trWrapper = new TagWrapper(3, "<table><tbody><tr>", "</tr></tbody></table>");

    wrapperMap = JsNamedArray.create();
    wrapperMap.put("option", selectWrapper);
    wrapperMap.put("optgroup", selectWrapper);
    wrapperMap.put("legend", new TagWrapper(1, "<fieldset>", "</fieldset>"));
    wrapperMap.put("thead", tableWrapper);
    wrapperMap.put("tbody", tableWrapper);
    wrapperMap.put("tfoot", tableWrapper);
    wrapperMap.put("colgroup", tableWrapper);
    wrapperMap.put("caption", tableWrapper);
    wrapperMap.put("tr", new TagWrapper(2, "<table><tbody>", "</tbody></table>"));
    wrapperMap.put("td", trWrapper);
    wrapperMap.put("th", trWrapper);
    wrapperMap.put("col", new TagWrapper(2, "<table><tbody></tbody><colgroup>",
        "</colgroup></table>"));
    wrapperMap.put("area", new TagWrapper(1, "<map>", "</map>"));
  }

  private static GQuery innerHtml(String html, Document doc) {
    return cleanHtmlString(html, doc);
  }

  protected static String[] jsArrayToString(JsArrayString array) {
    if (GWT.isScript()) {
      return JsUtils.castArrayString(array);
    } else {
      String result[] = new String[array.length()];
      for (int i = 0, l = result.length; i < l; i++) {
        result[i] = array.get(i);
      }
      return result;
    }
  }

  /**
   * Return a lazy version of the GQuery interface. Lazy function calls are simply queued up and not
   * executed immediately.
   */
  public static LazyGQuery<?> lazy() {
    return $().createLazy();
  }

  /**
   * Perform an ajax request to the server using POST.
   */
  public static Promise post(String url, Properties data, final Function onSuccess) {
    return Ajax.post(url, data, onSuccess);
  }

  public static <T extends GQuery> Class<T> registerPlugin(Class<T> plugin, Plugin<T> pluginFactory) {
    // TODO: decide whether change plugins type to java.util.list
    // Right now we only test static methods in gquery, so this is only needed when initializing
    // plugins shortcuts in gquery.
    if (GWT.isClient()) {
      if (plugins == null) {
        plugins = JsMap.createObject().cast();
      }
      plugins.put(plugin, pluginFactory);
    }
    return plugin;
  }

  /**
   * Provides a way to execute callback Functions based on one or more objects
   * that represent asynchronous events.
   *
   * Arguments can be of any Object, but normally you would pass Promises.
   * In the case you provide a GQuery object it will call the promise() method to return
   * a Promise which will be executed when the queue is resolved.
   * In the case you provide a normal Object, it will return a promise which will be immediately
   * resolved with the object as argument.
   * In the case you provide a Function it will executed and if the f(Object...) method returns
   * a new promise it will be used, otherwise we will use the returned object like in the last case.
   *
   * It Returns a new promise which will be finalized when all of its subordinates finish.
   * In the case of all subordinates are resolved correctly the promise will be resolved
   * otherwise it will be rejected.
   */
  public static Promise when(Object... subordinates) {
    return Deferred.when(subordinates);
  }

  /**
   * A constructor function that returns a chainable utility object with methods to register
   * multiple callbacks into callback queues, invoke callback queues, and relay the success
   * or failure state of any synchronous or asynchronous function.
   */
  public static Promise.Deferred Deferred() {
    return new Deferred();
  }

  public static SelectorEngine getSelectorEngine() {
    if (engine == null) {
      engine = GWT.create(SelectorEngine.class);
    }
    return engine;
  }

  private static native void scrollIntoViewImpl(Node n) /*-{
    if (n)
      n.scrollIntoView()
  }-*/;

  private static native void setElementValue(Element e, String value) /*-{
    e.value = value;
  }-*/;

  protected Node currentContext;

  protected String currentSelector;
  /**
   * Immutable array of matched elements, modify this using setArray.
   */
  private Element[] elements = new Element[0];

  /**
   * The nodeList of matched elements, modify this using setArray.
   */
  // TODO: remove this and use elements, change return type of get()
  private NodeList<Element> nodeList = JavaScriptObject.createArray().cast();

  private GQuery previousObject;

  private GQuery() {
  }

  private GQuery(Element element) {
    this(JsNodeArray.create(element));
  }

  protected GQuery(GQuery gq) {
    if (gq != null) {
      elements = gq.elements;
      nodeList = gq.nodeList;
      currentSelector = gq.currentSelector;
      currentContext = gq.currentContext;
    }
  }

  private GQuery(JsNodeArray nodes) {
    this(nodes.<NodeList<Element>> cast());
  }

  private GQuery(NodeList<Element> list) {
    setArray(list);
  }

  /**
   * Add elements to the set of matched elements if they are not included yet.
   *
   * It construct a new GQuery object and does not modify the original ones.
   *
   * It also update the selector appending the new one.
   */
  public GQuery add(GQuery elementsToAdd) {
    return pushStack(JsUtils.copyNodeList(nodeList, elementsToAdd.nodeList, true)
        .<JsNodeArray> cast(), "add", join(",", getSelector(), elementsToAdd.getSelector()));
  }

  /**
   * Add elements to the set of matched elements if they are not included yet.
   */
  public GQuery add(String selector) {
    return add($(selector));
  }

  /**
   * Add the previous selection to the current selection. Useful for traversing elements, and then
   * adding something that was matched before the last traversal.
   */
  public GQuery addBack() {
    return previousObject != null ? add(previousObject) : this;
  }

  /**
   * Adds the specified classes to each matched element.
   */
  public GQuery addClass(String... classes) {
    for (Element e : elements) {
      // issue 81 : ensure that the element is an Element node.
      if (Element.is(e)) {
        for (String clz : classes) {
          e.addClassName(clz);
        }
      }
    }
    return this;
  }

  /**
   * Insert content after each of the matched elements. The elements must already be inserted into
   * the document (you can't insert an element after another if it's not in the page).
   */
  public GQuery after(GQuery query) {
    return domManip(query, DomMan.AFTER);
  }

  /**
   * Insert content after each of the matched elements. The elements must already be inserted into
   * the document (you can't insert an element after another if it's not in the page).
   */
  public GQuery after(Node n) {
    return domManip($(n), DomMan.AFTER);
  }

  /**
   * Insert content after each of the matched elements. The elements must already be inserted into
   * the document (you can't insert an element after another if it's not in the page).
   */
  public GQuery after(String html) {
    return domManip(html, DomMan.AFTER);
  }

  private void allNextSiblingElements(Element firstChildElement, JsNodeArray result, Element elem,
      GQuery until, String filterSelector) {

    while (firstChildElement != null) {

      if (until != null && until.index(firstChildElement) != -1) {
        return;
      }

      if (firstChildElement != elem
          && (filterSelector == null || $(firstChildElement).is(filterSelector))) {
        result.addNode(firstChildElement);
      }
      firstChildElement = firstChildElement.getNextSiblingElement();
    }
  }

  private void allPreviousSiblingElements(Element firstChildElement, JsNodeArray result,
      GQuery until, String filterSelector) {
    while (firstChildElement != null) {
      if (until != null && until.index(firstChildElement) != -1) {
        return;
      }

      if (filterSelector == null || $(firstChildElement).is(filterSelector)) {
        result.addNode(firstChildElement);
      }

      firstChildElement = getPreviousSiblingElement(firstChildElement);
    }
  }

  /**
   * Add the previous selection to the current selection. Useful for traversing elements, and then
   * adding something that was matched before the last traversal.
   * @deprecated use addBack() instead
   */
  @Deprecated
  public GQuery andSelf() {
    return addBack();
  }

  /**
   *
   * The animate() method allows you to create animation effects on any numeric HTML Attribute,
   * CSS property, or color CSS property.
   *
   * Concerning to numeric properties, values are treated as a number of pixels unless otherwise
   * specified. The units em and % can be specified where applicable.
   *
   * By default animate considers css properties, if you wanted to animate element attributes you
   * should to prepend the symbol dollar to the attribute name. It's useful to animate svg elements.
   *
   * NOTE: The ability of animating attribute values is only available in gquery but not jquery
   *
   * Example:
   *
   * <pre class="code">
   *  // move the element from its original position to left:500px
   *  $("#foo").animate("left:'500'");
   *
   *  // Change the width html attribute of a table, note the symbol '$' to
   *  // tell gquery which it is an html-attribute instead of a css-property.
   *  $("table").animate("$width:'500'");
   * </pre>
   *
   * In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'.
   * These shortcuts allow for custom hiding and showing animations that take into account the
   * display type of the element. Animated properties can also be relative. If a value is supplied
   * with a leading += or -= sequence of characters, then the target value is computed by adding or
   * subtracting the given number from the current value of the property.
   *
   * Example:
   *
   * <pre class="code">
   *  // move the element from its original position to 500px to the left for 500ms and
   *  // change the background color of the element at the end of the animation
   *
   *  $("#foo").animate("left:'+=500'", new Function(){
   *                 public void f(Element e){
   *                   $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED);
   *                 }
   *              });
   * </pre>
   *
   * The default duration of the animation is 500ms.
   *
   * For color css properties, values can be specified via hexadecimal or rgb or literal values.
   *
   * Example:
   *
   * <pre class="code">
   *  $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)'");
   * </pre>
   *
   * @param stringOrProperties the property to animate : "cssName:'value'"
   * @param funcs an array of {@link Function} called once the animation is complete
   */
  public GQuery animate(Object stringOrProperties, Function... funcs) {
    return as(Effects).animate(stringOrProperties, funcs);
  }

  /**
   *
   * The animate() method allows you to create animation effects on any numeric HTML Attribute,
   * CSS property, or color CSS property.
   *
   * Concerning to numeric properties, values are treated as a number of pixels unless otherwise
   * specified. The units em and % can be specified where applicable.
   *
   * By default animate considers css properties, if you wanted to animate element attributes you
   * should to prepend the symbol dollar to the attribute name. It's useful to animate svg elements.
   *
   * NOTE: The ability of animating attribute values is only available in gquery but not jquery
   *
   * Example:
   *
   * <pre class="code">
   *  // move the element from its original position to left:500px for 500ms using a swing easing
   *  $("#foo").animate("left:'500'", 500, Easing.SWING);
   *
   *  // Change the width html attribute of a table, note the symbol '$' to
   *  // tell gquery which it is an html-attribute instead of a css-property.
   *  // the animation will last 400ms, and we use the LINEAR easing algorithm
   *  $("table").animate(Properties.create("{$width: '500', $border: '10'}"), 400, Easing.LINEAR);
   * </pre>
   *
   * In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'.
   * These shortcuts allow for custom hiding and showing animations that take into account the
   * display type of the element. Animated properties can also be relative. If a value is supplied
   * with a leading += or -= sequence of characters, then the target value is computed by adding or
   * subtracting the given number from the current value of the property.
   *
   * Example:
   *
   * <pre class="code">
   *  // move the element from its original position to 500px to the left and 5OOpx down for 400ms.
   *  // use a swing easing function for the transition
   *  $("#foo").animate(Properties.create("{top:'+=500px',left:'+=500px'}"), 400, Easing.SWING);
   * </pre>
   *
   * For color css properties, values can be specified via hexadecimal or rgb or literal values.
   *
   * Example:
   *
   * <pre class="code">
   *  $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)'"), 400, Easing.SWING);
   * </pre>
   *
   * @param stringOrProperties a String or a {@link Properties} object containing css properties to
   *          animate.
   * @param funcs an array of {@link Function} called once the animation is complete
   * @param duration the duration in milliseconds of the animation
   * @param easing the easing function to use for the transition
   */
  public GQuery animate(Object stringOrProperties, int duration, Easing easing, Function... funcs) {
    return as(Effects).animate(stringOrProperties, duration, easing, funcs);
  }

  /**
   * The animate() method allows you to create animation effects on any numeric HTML Attribute,
   * CSS property, or color CSS property.
   *
   * Concerning to numeric properties, values are treated as a number of pixels unless otherwise
   * specified. The units em and % can be specified where applicable.
   *
   * By default animate considers css properties, if you wanted to animate element attributes you
   * should to prepend the symbol dollar to the attribute name. It's useful to animate svg elements.
   *
   * NOTE: The ability of animating attribute values is only available in gquery but not jquery
   *
   * Example:
   *
   * <pre class="code">
   *  // move the element from its original position to left:500px for 500ms
   *  $("#foo").animate("left:'500'", 500);
   *
   *  // Change the width html attribute of a table, note the symbol '$' to
   *  // tell gquery which it is an html-attribute instead of a css-property.
   *  // the animation will last 400ms
   *  $("table").animate("$width:'500'"), 400);
   * </pre>
   *
   * In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'.
   * These shortcuts allow for custom hiding and showing animations that take into account the
   * display type of the element. Animated properties can also be relative. If a value is supplied
   * with a leading += or -= sequence of characters, then the target value is computed by adding or
   * subtracting the given number from the current value of the property.
   *
   * Example:
   *
   * <pre class="code">
   *  // move the element from its original position to 500px to the left for 1000ms and
   *  // change the background color of the element at the end of the animation
   *  $("#foo").animate("left:'+=500'", 1000, new Function(){
   *     public void f(Element e){
   *       $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED);
   *     }
   *  });
   * </pre>
   *
   * For color css properties, values can be specified via hexadecimal or rgb or literal values.
   *
   * Example:
   *
   * <pre class="code">
   *  $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)', 1000");
   * </pre>
   *
   * @param stringOrProperties the set of properties to animate : "cssName:'value'"
   * @param funcs an array of {@link Function} called once the animation is complete.
   */
  public GQuery animate(Object stringOrProperties, int duration, Function... funcs) {
    return as(Effects).animate(stringOrProperties, duration, funcs);
  }

  /**
   * Append content to the inside of every matched element. This operation is similar to doing an
   * appendChild to all the specified elements, adding them into the document.
   */
  public GQuery append(GQuery query) {
    return domManip(query, DomMan.APPEND);
  }

  /**
   * Append content to the inside of every matched element. This operation is similar to doing an
   * appendChild to all the specified elements, adding them into the document.
   */
  public GQuery append(Node n) {
    return domManip($(n), DomMan.APPEND);
  }

  /**
   * Append content to the inside of every matched element. This operation is similar to doing an
   * appendChild to all the specified elements, adding them into the document.
   */
  public GQuery append(String html) {
    return domManip(html, DomMan.APPEND);
  }

  /**
   * All of the matched set of elements will be inserted at the end of the element(s) specified by
   * the parameter other.
   *
   * The operation $(A).appendTo(B) is, essentially, the reverse of doing a regular $(A).append(B),
   * instead of appending B to A, you're appending A to B.
   */
  public GQuery appendTo(GQuery other) {
    other.append(this);
    return this;
  }

  /**
   * All of the matched set of elements will be inserted at the end of the element(s) specified by
   * the parameter other.
   *
   * The operation $(A).appendTo(B) is, essentially, the reverse of doing a regular $(A).append(B),
   * instead of appending B to A, you're appending A to B.
   */
  public GQuery appendTo(Node n) {
    GQuery a = $(n);
    GQuery b = this;
    a.append(b);
    return this;
  }

  /**
   * All of the matched set of elements will be inserted at the end of the element(s) specified by
   * the parameter other.
   *
   * The operation $(A).appendTo(B) is, essentially, the reverse of doing a regular $(A).append(B),
   * instead of appending B to A, you're appending A to B.
   */
  public GQuery appendTo(String html) {
    $(html).append(this);
    return this;
  }

  /**
   * Convert to Plugin interface provided by Class literal.
   */
  @SuppressWarnings("unchecked")
  public <T extends GQuery> T as(Class<T> plugin) {
    // GQuery is not a plugin for itself
    if (plugin == GQUERY) {
      return (T) this;
    } else if (plugins != null) {
      Plugin<?> p = plugins.get(plugin);
      if (p != null) {
        return (T) p.init(this);
      }
    }
    throw new RuntimeException("No plugin registered for class " + plugin.getName());
  }

  /**
   * Set a key/value object as properties to all matched elements.
   *
   * Example: $("img").attr(new Properties("src: 'test.jpg', alt: 'Test Image'"))
   */
  public GQuery attr(Properties properties) {
    for (String name : properties.keys()) {
      attr(name, properties.getStr(name));
    }
    return this;
  }

  /**
   * Access a property on the first matched element. This method makes it easy to retrieve a
   * property value from the first matched element. If the element does not have an attribute with
   * such a name, empty string is returned. Attributes include title, alt, src, href, width, style,
   * etc.
   */
  public String attr(String name) {
    return isEmpty() ? "" : get(0).getAttribute(name);
  }

  /**
   * Set a single property to a computed value, on all matched elements.
   */
  public GQuery attr(String key, Function closure) {
    int i = 0;
    for (Element e : elements) {
      Object val = closure.f(e.<com.google.gwt.dom.client.Element> cast(), i++);
      $(e).attr(key, val);
    }
    return this;
  }

  /**
   * Set a single property to a value, on all matched elements.
   */
  public GQuery attr(String key, Object value) {
    assert key != null : "key cannot be null";
    assert !"$H".equalsIgnoreCase(key) : "$H is a GWT reserved attribute. Changing its value will break your application.";

    getAttributeImpl().setAttribute(this, key, value);

    return this;
  }

  /**
   * Insert content before each of the matched elements. The elements must already be inserted into
   * the document (you can't insert an element before another if it's not in the page).
   */
  public GQuery before(GQuery query) {
    return domManip(query, DomMan.BEFORE);
  }

  /**
   * Insert content before each of the matched elements. The elements must already be inserted into
   * the document (you can't insert an element before another if it's not in the page).
   */
  public GQuery before(Node n) {
    return domManip($(n), DomMan.BEFORE);
  }

  /**
   * Insert content before each of the matched elements. The elements must already be inserted into
   * the document (you can't insert an element before another if it's not in the page).
   */
  public GQuery before(String html) {
    return domManip(html, DomMan.BEFORE);
  }

  /**
   * Binds a set of handlers to a particular Event for each matched element.
   *
   * The event handlers are passed as Functions that you can use to prevent default behavior. To
   * stop both default action and event bubbling, the function event handler has to return false.
   *
   * You can pass an additional Object data to your Function as the second parameter
   *
   */
  public GQuery bind(int eventbits, final Object data, final Function... funcs) {
    return as(Events).bind(eventbits, data, funcs);
  }

  /**
   * Binds a set of handlers to a particular Event for each matched element.
   *
   * The event handlers are passed as Functions that you can use to prevent default behavior. To
   * stop both default action and event bubbling, the function event handler has to return false.
   *
   */
  public GQuery bind(int eventbits, final Function... funcs) {
    return as(Events).bind(eventbits, null, funcs);
  }

  /**
   * Binds a set of handlers to a particular Event for each matched element.
   *
   * The event handlers are passed as Functions that you can use to prevent default behavior. To
   * stop both default action and event bubbling, the function event handler has to return false.
   *
   * You can pass an additional Object data to your Function as the second parameter
   *
   */
  public GQuery bind(String eventType, final Object data, final Function... funcs) {
    return as(Events).bind(eventType, data, funcs);
  }

  /**
   * Binds a set of handlers to a particular Event for each matched element.
   *
   * The event handlers are passed as Functions that you can use to prevent default behavior. To
   * stop both default action and event bubbling, the function event handler has to return false.
   *
   */
  public GQuery bind(String eventType, final Function... funcs) {
    return as(Events).bind(eventType, null, funcs);
  }

  /**
   * Bind Handlers or fire Events for each matched element.
   */
  private GQuery bindOrFire(int eventbits, final Object data, final Function... funcs) {
    if (funcs.length == 0) {
      return trigger(eventbits);
    } else {
      return bind(eventbits, data, funcs);
    }
  }

  /**
   * Bind Handlers or fire Events for each matched element.
   */
  private GQuery bindOrFire(String eventname, final Object data, final Function... funcs) {
    if (funcs.length == 0) {
      return as(Events).triggerHtmlEvent(eventname);
    } else {
      return bind(eventname, data, funcs);
    }
  }

  /**
   * Bind a set of functions to the blur event of each matched element. Or trigger the blur event if
   * no functions are provided.
   */
  public GQuery blur(Function... f) {
    bindOrFire(Event.ONBLUR, null, f);
    if (!isEmpty() && f.length == 0) {
      get(0).blur();
    }
    return this;
  }

  /**
   * Bind a set of functions to the change event of each matched element. Or trigger the event if no
   * functions are provided.
   */
  public GQuery change(Function... f) {
    return bindOrFire(Event.ONCHANGE, null, f);
  }

  /**
   * Get a set of elements containing all of the unique immediate children of each of the matched
   * set of elements. Also note: while parents() will look at all ancestors, children() will only
   * consider immediate child elements.
   */
  public GQuery children() {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      allNextSiblingElements(e.getFirstChildElement(), result, null, null, null);
    }
    return new GQuery(unique(result));
  }

  /**
   * Get a set of elements containing all of the unique children of each of the matched set of
   * elements. This set is filtered with the expressions that will cause only elements matching any
   * of the selectors to be collected.
   */
  public GQuery children(String... filters) {
    return children().filter(filters);
  }

  private void cleanGQData(Element... elements) {
    for (Element el : elements) {
      try {
        EventsListener.clean(el);
        removeData(el, null);
      } catch (Exception e) {
        // If for some reason event/data removal fails, do not break the app,
        // just log the error in dev-mode
        // e.g.: this happens when removing iframes which are no fully loaded.
        e.printStackTrace();
      }
    }
  }

  /**
   * Remove from the Effects queue all {@link Function} that have not yet been run.
   */
  public GQuery clearQueue() {
    return as(Queue).clearQueue();
  }

  /**
   * Remove from the queue all {@link Function} that have not yet been run.
   */
  public GQuery clearQueue(String queueName) {
    return as(Queue).clearQueue(queueName);
  }

  /**
   * Bind a set of functions to the click event of each matched element. Or trigger the event if no
   * functions are provided.
   */
  public GQuery click(Function... f) {
    return bindOrFire(Event.ONCLICK, null, f);
  }

  /**
   * Clone matched DOM Elements and select the clones. This is useful for moving copies of the
   * elements to another location in the DOM.
   */
  public GQuery clone() {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      result.addNode(e.cloneNode(true));
    }
    GQuery ret = new GQuery(result);
    ret.currentContext = currentContext;
    ret.currentSelector = currentSelector;
    return ret;
  }

  /**
   * Get the first ancestor element that matches the selector (for each matched element), beginning
   * at the current element and progressing up through the DOM tree.
   *
   * @param selector
   * @return
   */
  public GQuery closest(String selector) {
    return closest(selector, null);
  }

  /**
   * Get the first ancestor element that matches the selector (for each matched element), beginning
   * at the current element and progressing up through the DOM tree until reach the
   * <code>context</code> node.
   *
   * If no context is passed in then the context of the gQuery object will be used instead.
   *
   */
  public GQuery closest(String selector, Node context) {
    assert selector != null;

    if (context == null) {
      context = currentContext;
    }

    GQuery pos = posRegex.test(selector) ? $(selector, context) : null;
    JsNodeArray result = JsNodeArray.create();

    for (Element e : elements) {
      Element current = e;
      while (current != null && current.getOwnerDocument() != null && current != context) {
        boolean match = pos != null ? pos.index(current) > -1 : $(current).is(selector);
        if (match) {
          result.addNode(current);
          break;
        } else {
          current = current.getParentElement();
        }
      }
    }

    return $(unique(result));
  }

  /**
   * Returns a {@link Map} object as key a selector and as value the list of ancestor elements
   * matching this selectors, beginning at the first matched element and progressing up through the
   * DOM. This method allows retrieving the list of ancestors matching many selectors by traversing
   * the DOM only one time.
   *
   * @return
   */
  public JsNamedArray<NodeList<Element>> closest(String[] selectors) {
    return closest(selectors, null);
  }

  /**
   * Returns a {@link Map} object as key a selector and as value the list of ancestor elements
   * matching this selectors, beginning at the first matched element and progressing up through the
   * DOM until reach the <code>context</code> node.. This method allows retrieving the list of
   * ancestors matching many selectors by traversing the DOM only one time.
   *
   * @return
   */
  public JsNamedArray<NodeList<Element>> closest(String[] selectors, Node context) {
    JsNamedArray<NodeList<Element>> results = JsNamedArray.create();

    if (context == null) {
      context = currentContext;
    }

    Element first = get(0);
    if (first != null && selectors != null && selectors.length > 0) {
      JsNamedArray<GQuery> matches = JsNamedArray.create();
      for (String selector : selectors) {
        if (!matches.exists(selector)) {
          matches.put(selector, posRegex.test(selector) ? $(selector, context) : null);
        }
      }

      Element current = first;
      while (current != null && current.getOwnerDocument() != null && current != context) {
        // for each selector, check if the current element match it.
        for (String selector : matches.keys()) {

          GQuery pos = matches.get(selector);
          boolean match = pos != null ? pos.index(current) > -1 : $(current).is(selector);

          if (match) {
            JsNodeArray elementsMatchingSelector = results.get(selector).cast();
            if (elementsMatchingSelector == null) {
              elementsMatchingSelector = JsNodeArray.create();
              results.put(selector, elementsMatchingSelector);
            }
            elementsMatchingSelector.addNode(current);
          }
        }

        current = current.getParentElement();
      }
    }
    return results;
  }

  /**
   * Filter the set of elements to those that contain the specified text.
   */
  public GQuery contains(String text) {
    JsNodeArray array = JsNodeArray.create();
    for (Element e : elements) {
      if ($(e).text().contains(text)) {
        array.addNode(e);
      }
    }
    return $(array);
  }

  /**
   * Find all the child nodes inside the matched elements (including text nodes), or the content
   * document, if the element is an iframe.
   */
  public GQuery contents() {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      if (JsUtils.isWindow(e) || "iframe".equalsIgnoreCase(e.getTagName())) {
        result.addNode(getStyleImpl().getContentDocument(e));
      } else {
        NodeList<Node> children = e.getChildNodes();
        for (int i = 0, l = children.getLength(); i < l; i++) {
          result.addNode(children.getItem(i));
        }
      }
    }
    return new GQuery(unique(result));
  }

  public LazyGQuery<?> createLazy() {
    return GWT.create(GQuery.class);
  }

  /**
   * Set CSS a single style property on every matched element using type-safe enumerations.
   *
   * The best way to use this method (i.e. to generate a CssSetter) is to take the desired css
   * property defined in {@link CSS} class and call the {@link TakesCssValue#with(HasCssName)}
   * method on it.
   *
   * ex :
   *
   * <pre class="code">
   * $("#myDiv").css(CSS.TOP.with(Length.cm(15)));
   * $("#myDiv").css(CSS.BACKGROUND.with(RGBColor.SILVER, ImageValue.url(""),
   *               BackgroundRepeat.NO_REPEAT, BackgroundAttachment.FIXED,
   *               BackgroundPosition.CENTER));
   * $("#myDiv").css(CSS.BACKGROUND_ATTACHMENT.with(BackgroundAttachment.FIXED));
   *
   * </pre>
   *
   */
  public GQuery css(CssSetter... cssSetter) {
    for (Element e : elements) {
      for (CssSetter s : cssSetter) {
        s.applyCss(e);
      }
    }
    return this;
  }

  /**
   * Return a style property on the first matched element using type-safe enumerations.
   *
   * Ex : $("#myId").css(CSS.BACKGROUND_COLOR);
   */
  public String css(HasCssValue property) {
    return css(property, true);
  }

  /**
   * Return a style property on the first matched element using type-safe enumerations.
   *
   * The parameter force has a special meaning here: - When force is false, returns the value of the
   * css property defined in the style attribute of the element. - Otherwise it returns the real
   * computed value.
   *
   * For instance if you define 'display=none' not in the element style but in the css stylesheet,
   * it returns an empty string unless you pass the parameter force=true.
   *
   * Ex : $("#myId").css(CSS.WIDTH, true);
   */
  public String css(HasCssValue property, boolean force) {
    return css(property.getCssName(), force);
  }

  /**
   * Set a key/value object as style properties to all matched elements. This serves as the best way
   * to set a large number of style properties on all matched elements. You can use either js maps
   * or pure css syntax.
   *
   * Example:
   *
   * <pre class="code">
   *  $(".item").css(Properties.create("color: 'red', background:'blue'"))
   *  $(".item").css(Properties.create("color: red; background: blue;"))
   * </pre>
   */
  public GQuery css(Properties properties) {
    for (String property : properties.keys()) {
      css(property, properties.getStr(property));
    }
    return this;
  }

  /**
   * Return a style property on the first matched element.
   */
  public String css(String name) {
    return css(name, true);
  }

  /**
   * Return a style property on the first matched element.
   *
   * The parameter force has a special meaning here:
   * <ul>
   * <li>When force is false, returns the value of the css property defined in the style attribute
   * of the element.
   * <li>Otherwise it returns the real computed value.
   * </ul>
   *
   * For instance if you don't define 'display=none'in the element style but in the css stylesheet,
   * it returns an empty string unless you pass the parameter force=true.
   */
  public String css(String name, boolean force) {
    return isEmpty() ? "" : getStyleImpl().curCSS(get(0), name, force);
  }

  /**
   * Set a single style property to a value, on all matched elements.
   *
   */
  public GQuery css(String prop, String val) {
    for (Element e : elements) {
      getStyleImpl().setStyleProperty(e, prop, val);
    }
    return this;
  }

  /**
   * Set CSS a single style property on every matched element using type-safe enumerations. This
   * method allows you to set manually the value or set <i>inherit</i> value
   *
   * ex :
   *
   * <pre class="code">
   * $(#myId).css(CSS.TEXT_DECORATION, CSS.INHERIT);
   * </pre>
   */
  public GQuery css(TakesCssValue<?> cssProperty, String value) {
    return css(cssProperty.getCssName(), value);
  }

  /**
   * Returns the numeric value of a css property.
   */
  public double cur(String prop) {
    return cur(prop, false);
  }

  /**
   * Returns the numeric value of a css property.
   *
   * The parameter force has a special meaning: - When force is false, returns the value of the css
   * property defined in the set of style attributes. - When true returns the real computed value.
   */
  public double cur(String prop, boolean force) {
    return isEmpty() ? 0 : getStyleImpl().cur(get(0), prop, force);
  }

  /**
   * Return the value at the named data store for the first element in the set of matched
   * elements.
   */
  @SuppressWarnings("unchecked")
  public <T> T data(String name) {
    return isEmpty() ? null : (T) data(get(0), name, null);
  }

  /**
   * Return the value at the named data store for the first element in the set of matched
   * elements, as set by data(name, value), with desired return type.
   *
   * @param clz return type class literal
   */
  public <T> T data(String name, Class<? extends T> clz) {
    return isEmpty() ? null : data(get(0), name, null, clz);
  }

  /**
   * Store arbitrary data associated with the matched elements in the named data store.
   */
  public GQuery data(String name, Object value) {
    for (Element e : elements()) {
      data(e, name, value);
    }
    return this;
  }

  /**
   * Bind a set of functions to the dblclick event of each matched element. Or trigger the event if
   * no functions are provided.
   */
  public GQuery dblclick(Function... f) {
    return bindOrFire(Event.ONDBLCLICK, null, f);
  }

  /**
   * Insert a delay (in ms) in the GQuery queue, and optionally execute one o more functions if
   * provided when the delay finishes. It uses the effects queue namespace, so you can stack any of
   * the methods in the effects plugin.
   *
   * Example:
   *
   * <pre class="code">
   * $("#foo").slideUp(300)
   *          .delay(800)
   *          .fadeIn(400);
   * </pre>
   *
   * When this statement is executed, the element slides up for 300 milliseconds and then pauses for
   * 800 milliseconds before fading in for 400 milliseconds. Aditionally after those 800
   * milliseconds the element color is set to red.
   *
   * NOTE that this methods affects only methods which uses the queue like effects. So the following
   * example is wrong:
   *
   * <pre>
   * $("#foo").css(CSS.COLOR.with(RGBColor.RED)).delay(800).css(CSS.COLOR.with(RGBColor.BLACK));
   * </pre>
   *
   * The code above will not insert a delay of 800 ms between the css() calls ! For this kind of
   * behavior, you should execute these methods puting them in inline functions passed as argument
   * to the delay() method, or adding them to the queue.
   *
   * <pre>
   * $("#foo").css(CSS.COLOR.with(RGBColor.RED)).delay(800, lazy().css(CSS.COLOR.with(RGBColor.BLACK)).done());
   * $("#foo").css(CSS.COLOR.with(RGBColor.RED)).delay(800).queue(lazy().css(CSS.COLOR.with(RGBColor.BLACK)).dequeue().done());
   * </pre>
   */
  public GQuery delay(int milliseconds, Function... f) {
    return as(Queue).delay(milliseconds, f);
  }

  /**
   * Insert a delay (in ms) in the queue identified by the <code>queueName</code> parameter, and
   * optionally execute one o more functions if provided when the delay finishes.
   *
   * If <code>queueName</code> is null or equats to 'fx', the delay will be inserted to the Effects
   * queue.
   *
   * Example :
   *
   * <pre class="code">
   * $("#foo").queue("colorQueue", lazy().css(CSS.COLOR.with(RGBColor.RED)).dequeue("colorQueue").done())
   *          .delay(800, "colorQueue")
   *          .queue("colorQueue", lazy().css(CSS.COLOR.with(RGBColor.BLACK)).dequeue("colorQueue").done());
   * </pre>
   *
   * When this statement is executed, the text color of the element changes to red and then wait for
   * 800 milliseconds before changes the text color to black.
   *
   */
  public GQuery delay(int milliseconds, String queueName, Function... f) {
    return as(Queue).delay(milliseconds, queueName, f);
  }

  /**
   * Attach <code>handlers</code> to one or more events for all elements that match the
   * <code>selector</code>, now or in the future, based on a specific set of root elements.
   *
   * Example:
   *
   * <pre>
   * $("table").delegate("td", Event.ONCLICK, new Function(){
   *  public void f(Element e){
   *  $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
   *  }
   * });
   * </pre>
   *
   * This code above add an handler on click event on all cell (the existing oneand the future cell)
   * of all table. This code is equivalent to :
   *
   * <pre>
   * $("table").each(new Function(){
   *  public void f(Element table){
   *   $("td", table).live(Event.ONCLICK, new Function(){
   *      public void f(Element e){
   *      $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
   *    }
   *  }
   * });
   *
   * </pre>
   *
   * You can attach the handlers to many events by using the '|' operator ex:
   *
   * <pre>
   *  $("div.main").delegate(".subMain", Event.ONCLICK | Event.ONDBLCLICK, new Function(){...});
   * </pre>
   * @deprecated use {@link #on(String, String, Function...)}
   */
  public GQuery delegate(String selector, int eventbits, Function... handlers) {
    return delegate(selector, eventbits, null, handlers);
  }

  /**
   * Attach <code>handlers</code> to one or more events for all elements that match the
   * <code>selector</code>, now or in the future, based on a specific set of root elements. The
   * <code>data</code> parameter allows us to pass data to the handler.
   *
   * Example:
   *
   * <pre>
   * $("table").delegate("td", "click", new Function(){
   *  public void f(Element e){
   *  $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
   *  }
   * });
   * </pre>
   *
   * This code above add an handler on click event on all cell (the existing oneand the future cell)
   * of all table. This code is equivalent to :
   *
   * <pre>
   * $("table").each(new Function(){
   *  public void f(Element table){
   *   $("td", table).live("click", new Function(){
   *      public void f(Element e){
   *      $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
   *    }
   *  }
   * });
   *
   * </pre>
   *
   * You can pass attach the handlers to many events by using the '|' operator ex:
   *
   * <pre>
   *  $("div.main").delegate(".subMain", Event.ONCLICK | Event.ONDBLCLICK, new Function(){...});
   * </pre>
   * @deprecated use {@link #on(String, String, Object, Function...)}
   */
  public GQuery delegate(String selector, int eventbits, Object data, Function... handlers) {

    for (Element e : elements) {
      $(selector, e).live(eventbits, data, handlers);
    }

    return this;
  }

  /**
   * Attach <code>handlers</code> to one or more events for all elements that match the
   * <code>selector</code>, now or in the future, based on a specific set of root elements.
   *
   * Example:
   *
   * <pre>
   * $("table").delegate("td", "click", new Function(){
   *  public void f(Element e){
   *  $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
   *  }
   * });
   * </pre>
   *
   * This code above add an handler on click event on all cell (the existing oneand the future cell)
   * of all table. This code is equivalent to :
   *
   * <pre>
   * $("table").each(new Function(){
   *  public void f(Element table){
   *   $("td", table).live("click", new Function(){
   *      public void f(Element e){
   *      $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
   *    }
   *  }
   * });
   *
   * </pre>
   *
   * You can pass attach the handlers to many events by specifying a String with espaced event type.
   * ex:
   *
   * <pre>
   *  $("div.main").delegate(".subMain", "click dblclick", new Function(){...});
   * </pre>
   *
   * </pre>
   * @deprecated use {@link #on(String, String, Function...)}
   */
  public GQuery delegate(String selector, String eventType, Function... handlers) {
    return delegate(selector, eventType, null, handlers);
  }

  /**
   * Attach <code>handlers</code> to one or more events for all elements that match the
   * <code>selector</code>, now or in the future, based on a specific set of root elements.
   *
   * Example:
   *
   * <pre>
   * $("table").delegate("td", "click", new Function(){
   *  public void f(Element e){
   *  $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
   *  }
   * });
   * </pre>
   *
   * This code above add an handler on click event on all cell (the existing oneand the future cell)
   * of all table. This code is equivalent to :
   *
   * <pre>
   * $("table").each(new Function(){
   *  public void f(Element table){
   *   $("td", table).live("click", new Function(){
   *      public void f(Element e){
   *      $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED));
   *    }
   *  }
   * });
   *
   * You can pass attach the handlers to many events by specifying a String with espaced event type.
   * ex:
   *
   * <pre>
   *  $("div.main").delegate(".subMain", "click dblclick", new Function(){...});
   * </pre>
   *
   * </pre>
   * @deprecated use {@link #on(String, String, Object, Function...)}
   */
  public GQuery delegate(String selector, String eventType, Object data, Function... handlers) {
    for (Element e : elements) {
      $(selector, e).live(eventType, data, handlers);
    }

    return this;
  }

  /**
   * Execute the next function on the Effects queue for the matched elements. This method is usefull
   * to tell when a function you add in the Effects queue is ended and so the next function in the
   * queue can start.
   *
   * Note: you should be sure to call dequeue() in all functions of a queue chain, otherwise the
   * queue execution will be stopped.
   */
  public GQuery dequeue() {
    return as(Queue).dequeue();
  }

  /**
   * Execute the next function on the queue named as queueName for the matched elements. This method
   * is usefull to tell when a function you add in the Effects queue is ended and so the next
   * function in the queue can start.
   */
  public GQuery dequeue(String queueName) {
    return as(Queue).dequeue(queueName);
  }

  /**
   * Detach all matched elements from the DOM. This method is the same than {@link #remove()} method
   * except all data and event handlers are not remove from the element. This method is useful when
   * removed elements are to be reinserted into the DOM at a later time.
   */
  public GQuery detach() {
    return remove(null, false);
  }

  /**
   * Detach from the DOM all matched elements filtered by the <code>filter</code>.. This method is
   * the same than {@link #remove(String)} method except all data and event handlers are not remove
   * from the element. This method is useful when removed elements are to be reinserted into the DOM
   * at a later time.
   */
  public GQuery detach(String filter) {
    return remove(filter, false);
  }

  /**
   * Remove all event handlers previously attached using {@link #live(String, Function)}. In order
   * for this method to function correctly, the selector used with it must match exactly the
   * selector initially used with {@link #live(String, Function)}.
   * 
   * @deprecated use {@link #off(String, String)} instead
   */
  public GQuery die() {
    return die(0);
  }

  /**
   * Remove an event handlers previously attached using {@link #live(int, Function)} In order for
   * this method to function correctly, the selector used with it must match exactly the selector
   * initially used with {@link #live(int, Function)}.
   * @deprecated use {@link #off(String)}
   */
  public GQuery die(int eventbits) {
    return as(Events).die(eventbits);
  }

  /**
   * Remove an event handlers previously attached using {@link #live(String, Function)} In order for
   * this method to function correctly, the selector used with it must match exactly the selector
   * initially used with {@link #live(String, Function)}.
   */
  public GQuery die(String eventName) {
    return as(Events).die(eventName);
  }

  private GQuery domManip(GQuery g, DomMan type, Element... elms) {
    JsNodeArray newNodes = JsNodeArray.create();
    if (elms.length == 0) {
      elms = elements;
    }
    for (int i = 0, l = elms.length; i < l; i++) {
      Element e = elms[i];
      if (e.getNodeType() == Node.DOCUMENT_NODE) {
        e = e.<Document> cast().getBody();
      }
      for (int j = 0, size = g.size(); j < size; j++) {
        // Widget w = getAssociatedWidget(g.get(j));
        // GqUi.detachWidget(w);

        Node n = g.get(j);
        // If an element selected is inserted elsewhere, it will be moved into the target (not
        // cloned).
        // If there is more than one target element, however, cloned copies of the inserted element
        // will be created for each target after the first
        if (i > 0) {
          n = n.cloneNode(true);
        }
        switch (type) {
          case PREPEND:
            newNodes.addNode(e.insertBefore(n, e.getFirstChild()));
            break;
          case APPEND:
            newNodes.addNode(e.appendChild(n));
            break;
          case AFTER:
            newNodes.addNode(e.getParentNode().insertBefore(n, e.getNextSibling()));
            break;
          case BEFORE:
            newNodes.addNode(e.getParentNode().insertBefore(n, e));
            break;
        }
        EventsListener.rebind(n.<Element> cast());
        // GqUi.attachWidget(w);
      }
    }
    // TODO: newNodes.size() > g.size() makes testRebind fail
    if (newNodes.size() >= g.size()) {
      g.setArray(newNodes);
    }
    return this;
  }

  // TODO: this should be handled by the other domManip method
  private GQuery domManip(String htmlString, DomMan type) {
    JsMap<Document, GQuery> cache = JsMap.createObject().cast();
    for (Element e : elements) {
      Document d = JsUtils.getOwnerDocument(e);
      GQuery g = cache.get(d);
      if (g == null) {
        g = cleanHtmlString(htmlString, d);
        cache.put(d, g);
      }
      domManip(g.clone(), type, e);
    }
    return this;
  }

  /**
   * Run one or more Functions over each element of the GQuery. You have to override one of these
   * funcions: public void f(Element e) public String f(Element e, int i)
   */
  public GQuery each(Function... f) {
    if (f != null) {
      for (Function f1 : f) {
        if (f1 != null) {
          int i = 0;
          for (Element e : elements) {
            f1.f(e.<com.google.gwt.dom.client.Element> cast(), i++);
          }
        }
      }
    }
    return this;
  }

  /**
   * Returns the working set of nodes as a Java array. <b>Do NOT</b> attempt to modify this array,
   * e.g. assign to its elements, or call Arrays.sort()
   */
  public Element[] elements() {
    return elements;
  }

  /**
   * Remove all child nodes from the set of matched elements. In the case of a document element, it
   * removes all the content You should call this method whenever you create a new iframe and you
   * want to add dynamic content to it.
   */
  public GQuery empty() {
    for (Element e : elements) {
      if (e.getNodeType() == Element.DOCUMENT_NODE) {
        getStyleImpl().emptyDocument(e.<Document> cast());
      } else {
        Node c = e.getFirstChild();
        while (c != null) {
          removeData(c.<Element> cast(), null);
          WidgetsUtils.detachWidget(getAssociatedWidget(e));
          EventsListener.clean(c.<Element> cast());
          e.removeChild(c);
          c = e.getFirstChild();
        }
      }
    }
    return this;
  }

  /**
   * Revert the most recent 'destructive' operation, changing the set of matched elements to its
   * previous state (right before the destructive operation).
   */
  public GQuery end() {
    return previousObject != null ? previousObject : new GQuery();
  }

  /**
   * Reduce GQuery to element in the specified position. This method accept negative index. A
   * negative index is counted from the end of the matched set:
   *
   * Example:
   *
   * <pre>
   *  $("div").eq(0) will reduce the matched set to the first matched div
   *  $("div").eq(1) will reduce the matched set to the second matched div
   *
   *  $("div").eq(-1) will reduce the matched set to the last matched div
   *  $("div").eq(-2) will reduce the matched set to the second-to-last matched div
   *  ...
   * </pre>
   */
  public GQuery eq(int pos) {
    return $(get(pos));
  }

  /**
   * Bind a set of functions to the error event of each matched element. Or trigger the event if no
   * functions are provided.
   */
  public GQuery error(Function... f) {
    return bindOrFire(Event.ONERROR, null, f);
  }

  /**
   * Fade in all matched elements by adjusting their opacity. The effect will take 1000 milliseconds
   * to complete
   */
  public GQuery fadeIn(Function... f) {
    return as(Effects).fadeIn(f);
  }

  /**
   * Fade in all matched elements by adjusting their opacity.
   */
  public GQuery fadeIn(int millisecs, Function... f) {
    return as(Effects).fadeIn(millisecs, f);
  }

  /**
   * Fade the opacity of all matched elements to a specified opacity and firing
   * an optional callback after completion. Only the opacity is adjusted for
   * this animation, meaning that all of the matched elements should already
   * have some form of height and width associated with them.
   */
  public GQuery fadeTo(int millisecs, double opacity, Function... f) {
    return as(Effects).fadeTo(millisecs, opacity, f);
  }

  /**
   * Fade the opacity of all matched elements to a specified opacity and firing
   * an optional callback after completion. Only the opacity is adjusted for
   * this animation, meaning that all of the matched elements should already
   * have some form of height and width associated with them.
   */
  public GQuery fadeTo(double opacity, Function... f) {
    return as(Effects).fadeTo(opacity, f);
  }

  /**
   * Fade out all matched elements by adjusting their opacity. The effect will take 1000
   * milliseconds to complete
   */
  public GQuery fadeOut(Function... f) {
    return as(Effects).fadeOut(f);
  }

  /**
   * Fade out all matched elements by adjusting their opacity.
   */
  public GQuery fadeOut(int millisecs, Function... f) {
    return as(Effects).fadeOut(millisecs, f);
  }

  /**
   * Toggle the visibility of all matched elements by adjusting their opacity and firing an optional
   * callback after completion. Only the opacity is adjusted for this animation, meaning that all of
   * the matched elements should already have some form of height and width associated with them.
   */
  public Effects fadeToggle(int millisecs, Function... f) {
    return as(Effects).fadeToggle(millisecs, f);
  }

  /**
   * Removes all elements from the set of matched elements that do not match the specified function.
   * The function is called with a context equal to the current element. If the function returns
   * false, then the element is removed - anything else and the element is kept.
   */
  public GQuery filter(Predicate filterFn) {
    JsNodeArray result = getSelectorEngine().filter(nodeList, filterFn).cast();
    return pushStack(result, "filter", currentSelector);
  }

  /**
   * Removes all elements from the set of matched elements that do not pass the specified css
   * expression. This method is used to narrow down the results of a search.
   * By default it works for either detached and attached elements unless
   * {@link SelectorEngine#filterDetached} is set to false.
   */
  public GQuery filter(String... filters) {
    String selector = join(", ", filters);
    JsNodeArray result = getSelectorEngine().filter(nodeList, selector).cast();
    return pushStack(result, "filter", selector);
  }

  /**
   * Removes all elements from the set of matched elements that do not pass the specified css
   * expression. This method is used to narrow down the results of a search.
   * Setting filterDetached parameter to true, means that we should consider detached elements
   * as well which implies some performance penalty.
   */
  public GQuery filter(boolean filterDetached, String... filters) {
    String selector = join(", ", filters);
    JsNodeArray result = getSelectorEngine().filter(nodeList, selector, filterDetached).cast();
    return pushStack(result, "filter", selector);
  }

  /**
   * Removes all elements from the set of matched elements that do not pass the specified css
   * expression. This method is used to narrow down the results of a search.
   * Setting considerDetached parameter to true, means that we should consider detached elements
   * as well which implies some performance penalties.
   */
  public GQuery filter(boolean filterDetached, String selector) {
    if (selector.isEmpty()) {
      return this;
    }
    JsNodeArray result = getSelectorEngine().filter(nodeList, selector, filterDetached).cast();
    return pushStack(result, "filter", selector);
  }

  /**
   * Searches for all elements that match the specified css expression. This method is a good way to
   * find additional descendant elements with which to process.
   *
   * Provide a comma-separated list of expressions to apply multiple filters at once.
   */
  public GQuery find(String... filters) {
    JsNodeArray array = JsNodeArray.create();
    for (String selector : filters) {
      for (Element e : elements) {
        for (Element c : $(selector, e).elements) {
          array.addNode(c);
        }
      }
    }
    return pushStack(unique(array), "find", filters[0]);
  }

  /**
   * Reduce the set of matched elements to the first in the set.
   */
  public GQuery first() {
    return eq(0);
  }

  /**
   * Bind a set of functions to the focus event of each matched element. Or trigger the event and
   * move the input focus to the first element if no functions are provided.
   */
  public GQuery focus(Function... f) {
    bindOrFire(Event.ONFOCUS, null, f);
    if (!isEmpty() && f.length == 0) {
      get(0).focus();
    }
    return this;
  }

  /**
   * Return all elements matched in the GQuery as a NodeList. @see #elements() for a method which
   * returns them as an immutable Java array.
   */
  public NodeList<Element> get() {
    return nodeList;
  }

  /**
   * Return the ith element matched. This method accept negative index. A negative index is counted
   * from the end of the matched set.
   *
   * Example:
   *
   * <pre>
   *  $("div").get(0) will return the first matched div
   *  $("div").get(1) will return the second matched div
   *
   *  $("div").get(-1) will return the last matched div
   *  $("div").get(-2) will return the secont-to-last matched div
   *  ...
   * </pre>
   */
  public Element get(int i) {
    int l = elements.length;
    if (i >= 0 && i < l) {
      return elements[i];
    }
    if (i < 0 && l + i >= 0) {
      return elements[l + i];
    }
    return null;
  }

  public Node getContext() {
    return currentContext;
  }

  /**
   * Return the previous set of matched elements prior to the last destructive operation (e.g.
   * query)
   */
  public GQuery getPreviousObject() {
    return end();
  }

  private native Element getPreviousSiblingElement(Element elem) /*-{
    var sib = elem.previousSibling;
    while (sib && sib.nodeType != 1)
      sib = sib.previousSibling;
    return sib;
  }-*/;

  /**
   * Return the selector representing the current set of matched elements.
   */
  public String getSelector() {
    return currentSelector;
  }

  /**
   * Returns true any of the specified classes are present on any of the matched Reduce the set of
   * matched elements to all elements after a given position. The position of the element in the set
   * of matched elements starts at 0 and goes to length - 1.
   */
  public GQuery gt(int pos) {
    return slice(pos + 1, -1);
  }

  /**
   * Reduce the set of matched elements to those that have a descendant that matches the Element.
   */
  public GQuery has(final Element elem) {
    return filter(new Predicate() {
      public boolean f(Element e, int index) {
        return contains(e, elem);
      }
    });
  }

  /**
   * Reduce the set of matched elements to those that have a descendant that matches the selector.
   */
  public GQuery has(final String selector) {
    return filter(new Predicate() {
      public boolean f(Element e, int index) {
        return !$(selector, e).isEmpty();
      }
    });
  }

  /**
   * Returns true any of the specified classes are present on any of the matched elements.
   */
  public boolean hasClass(String... classes) {
    for (Element e : elements) {
      for (String clz : classes) {
        if (hasClass(e, clz)) {
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Get the current computed, pixel, height of the first matched element. It does not include
   * margin, padding nor border.
   */
  public int height() {
    return (int) cur("height", true);
  }

  /**
   * Set the height of every element in the matched set.
   */
  public GQuery height(int height) {
    for (Element e : elements) {
      e.getStyle().setPropertyPx("height", height);
    }
    return this;
  }

  /**
   * Set the height style property of every matched element. It's useful for using 'percent' or 'em'
   * units Example: $(".a").height("100%")
   */
  public GQuery height(String height) {
    return css("height", height);
  }

  /**
   * Make invisible all matched elements.
   */
  public GQuery hide() {
    for (Element e : elements) {
      String currentDisplay = getStyleImpl().curCSS(e, "display", false);
      Object old = data(e, OLD_DISPLAY, null);
      if (old == null && currentDisplay.length() != 0 && !"none".equals(currentDisplay)) {
        data(e, OLD_DISPLAY, currentDisplay);
      }
    }

    // Set the display value in a separate for loop to avoid constant reflow
    // Reflows is very bad in performance point of view
    for (Element e : elements) {
      e.getStyle().setDisplay(Display.NONE);
    }

    return this;
  }

  /**
   * Bind a function to the mouseover event of each matched element. A method for simulating
   * hovering (moving the mouse on, and off, an object). This is a custom method which provides an
   * 'in' to a frequent task. Whenever the mouse cursor is moved over a matched element, the first
   * specified function is fired. Whenever the mouse moves off of the element, the second specified
   * function fires.
   *
   * Since GQuery 1.4.0, this method binds handlers for both mouseenter and mouseleave events.
   */
  public GQuery hover(Function fover, Function fout) {
    return bind("mouseenter", fover).bind("mouseleave", fout);
  }

  /**
   * Get the innerHTML of the first matched element.
   */
  public String html() {
    return isEmpty() ? "" : get(0).getInnerHTML();
  }

  /**
   * Set the innerHTML of every matched element.
   */
  public GQuery html(String html) {
    for (Element e : elements) {
      if (e.getNodeType() == Node.DOCUMENT_NODE) {
        e = e.<Document> cast().getBody();
      }
      e.setInnerHTML(html);
    }
    return this;
  }

  /**
   * Get the id of the first matched element.
   */
  public String id() {
    return attr("id");
  }

  /**
   * Set the id of the first matched element.
   */
  public GQuery id(String id) {
    return eq(0).attr("id", id);
  }

  /**
   * Find the index of the specified Element.
   */
  public int index(Element element) {
    int i = 0;
    for (Element e : elements) {
      if (e == element) {
        return i;
      }
      i++;
    }
    return -1;
  }

  /**
   * Return the position of the first matched element in relation with its sibblings.
   */
  public int index() {
    return prevAll().size();
  }

  /**
   * Returns the inner height of the first matched element, including padding but not the vertical
   * scrollbar height, border, or margin.
   */
  public int innerHeight() {
    return (int) cur("clientHeight", true);
  }

  /**
   * Returns the inner width of the first matched element, including padding but not the vertical
   * scrollbar width, border, or margin.
   */
  public int innerWidth() {
    return (int) cur("clientWidth", true);
  }

  /**
   * Insert all of the matched elements after another, specified, set of elements.
   */
  public GQuery insertAfter(Element elem) {
    return insertAfter($(elem));
  }

  /**
   * Insert all of the matched elements after another, specified, set of elements.
   */
  public GQuery insertAfter(GQuery query) {
    for (Element e : elements) {
      query.after(e);
    }
    return this;
  }

  /**
   * Insert all of the matched elements after another, specified, set of elements.
   */
  public GQuery insertAfter(String selector) {
    return insertAfter($(selector));
  }

  /**
   * Insert all of the matched elements before another, specified, set of elements.
   *
   * The elements must already be inserted into the document (you can't insert an element after
   * another if it's not in the page).
   */
  public GQuery insertBefore(Element item) {
    return insertBefore($(item));
  }

  /**
   * Insert all of the matched elements before another, specified, set of elements.
   *
   * The elements must already be inserted into the document (you can't insert an element after
   * another if it's not in the page).
   */
  public GQuery insertBefore(GQuery query) {
    for (Element e : elements) {
      query.before(e);
    }
    return this;
  }

  /**
   * Insert all of the matched elements before another, specified, set of elements.
   *
   * The elements must already be inserted into the document (you can't insert an element after
   * another if it's not in the page).
   */
  public GQuery insertBefore(String selector) {
    return insertBefore($(selector));
  }

  /**
   * Checks the current selection against an expression and returns true, if at least one element of
   * the selection fits the given expression. Does return false, if no element fits or the
   * expression is not valid.
   */
  public boolean is(String... filters) {
    return !filter(filters).isEmpty();
  }

  /**
   * Returns true if the number of matched elements is 0.
   */
  public boolean isEmpty() {
    return size() == 0;
  }

  /**
   * Return true if the first element is visible.isVisible.
   */
  public boolean isVisible() {
    return isEmpty() ? false : getStyleImpl().isVisible(get(0));
  }

  /**
   * Bind a set of functions to the keydown event of each matched element. Or trigger the event if
   * no functions are provided.
   */
  public GQuery keydown(Function... f) {
    return bindOrFire(Event.ONKEYDOWN, null, f);
  }

  /**
   * Trigger a keydown event passing the key pushed.
   */
  public GQuery keydown(int key) {
    return trigger(Event.ONKEYDOWN, key);
  }

  /**
   * Bind a set of functions to the keypress event of each matched element. Or trigger the event if
   * no functions are provided.
   */
  public GQuery keypress(Function... f) {
    return bindOrFire(Event.ONKEYPRESS, null, f);
  }

  /**
   * Trigger a keypress event passing the key pushed.
   */
  public GQuery keypress(int key) {
    return trigger(Event.ONKEYPRESS, key);
  }

  /**
   * Bind a set of functions to the keyup event of each matched element. Or trigger the event if no
   * functions are provided.
   */
  public GQuery keyup(Function... f) {
    return bindOrFire(Event.ONKEYUP, null, f);
  }

  /**
   * Trigger a keyup event passing the key pushed.
   */
  public GQuery keyup(int key) {
    return trigger(Event.ONKEYUP, key);
  }

  /**
   * Reduce the set of matched elements to the final one in the set.
   */
  public GQuery last() {
    return eq(size() - 1);
  }

  /**
   * Returns the computed left position of the first element matched.
   */
  public int left() {
    return (int) cur("left", true);
  }

  /**
   * Returns the number of elements currently matched. The size function will return the same value.
   */
  public int length() {
    return size();
  }

  /**
   * Attach a handler for this event to all elements which match the current selector, now and in
   * the future.
   * @deprecated use {@link #on(String, Function...)}
   */
  public GQuery live(int eventbits, Function... funcs) {
    return as(Events).live(eventbits, null, funcs);
  }

  /**
   * Attach a handler for this event to all elements which match the current selector, now and in
   * the future.
   * @deprecated use {@link #on(String, Object, Function...)}
   */
  public GQuery live(int eventbits, Object data, Function... funcs) {
    return as(Events).live(eventbits, data, funcs);
  }

  /**
   * <p>
   * Attach a handler for this event to all elements which match the current selector, now and in
   * the future.
   * <p>
   * Ex :
   *
   * <pre>
   * $(".clickable").live("click", new Function(){
   *  public void f(Element e){
   *    $(e).css(CSS.COLOR.with(RGBColor.RED));
   *  }
   * });
   *  </pre>
   *
   * With this code, all elements with class "clickable" present in the DOM or added to the DOM in
   * the future will be clickable. The text color will be changed to red when they will be clicked.
   * So if after in the code, you add another element :
   *
   * <pre>
   * $("body").append("<div class='clickable'>Click me and I will be red</div>");
   * </pre>
   *
   * The click on this new element will also trigger the handler.
   * </p>
   * <p>
   * In the same way, if you add "clickable" class on some existing element, these elements will be
   * clickable also.
   * </p>
   * <p>
   * <h3>important remarks</h3>
   * <ul>
   * <li>
   * The live method should be always called after a selector</li>
   * <li>
   * Live events are bound to the context of the {@link GQuery} object :
   *
   * <pre>
   * $(".clickable", myElement).live("click", new Function(){
   *  public void f(Element e){
   *    $(e).css(CSS.COLOR.with(RGBColor.RED));
   *  }
   * });
   * </pre>
   * The {@link Function} will be called only on elements having the class "clickable" and being
   * descendant of myElement.</li>
   * </ul>
   * </p>
   * @deprecated use {@link #on(String, Function...)}
   */
  public GQuery live(String eventName, Function... funcs) {
    return as(Events).live(eventName, null, funcs);
  }

  /**
   * <p>
   * Attach a handler for this event to all elements which match the current selector, now and in
   * the future. The <code>data</code> parameter allows us to pass data to the handler.
   * <p>
   * Ex :
   *
   * <pre>
   * $(".clickable").live("click", new Function(){
   *  public void f(Element e){
   *    $(e).css(CSS.COLOR.with(RGBColor.RED));
   *  }
   * });
   *  </pre>
   *
   * With this code, all elements with class "clickable" present in the DOM or added to the DOM in
   * the future will be clickable. The text color will be changed to red when they will be clicked.
   * So if after in the code, you add another element :
   *
   * <pre>
   * $("body").append("<div class='clickable'>Click me and I will be red</div>");
   * </pre>
   *
   * The click on this new element will also trigger the handler.
   * </p>
   * <p>
   * In the same way, if you add "clickable" class on some existing element, these elements will be
   * clickable also.
   * </p>
   * <p>
   * <h3>important remarks</h3>
   * <ul>
   * <li>
   * The live method should be always called after a selector</li>
   * <li>
   * Live events are bound to the context of the {@link GQuery} object :
   *
   * <pre>
   * $(".clickable", myElement).live("click", new Function(){
   *  public void f(Element e){
   *    $(e).css(CSS.COLOR.with(RGBColor.RED));
   *  }
   * });
   * </pre>
   * The {@link Function} will be called only on elements having the class "clickable" and being
   * descendant of myElement.</li>
   * </ul>
   * </p>
   * @deprecated use {@link #on(String, Object, Function...)}
   */
  public GQuery live(String eventName, Object data, Function... funcs) {
    return as(Events).live(eventName, data, funcs);
  }

  /**
   * Bind a function to the load event of each matched element.
   */
  @Deprecated
  public GQuery load(Function f) {
    return bind(Event.ONLOAD, f);
  }

  /**
   * Load data from the server and place the returned HTML into the matched element.
   *
   * The url allows us to specify a portion of the remote document to be inserted. This is achieved
   * with a special syntax for the url parameter. If one or more space characters are included in
   * the string, the portion of the string following the first space is assumed to be a GQuery
   * selector that determines the content to be loaded.
   *
   */
  public GQuery load(String url) {
    return load(url, null, null);
  }

  /**
   * Load data from the server and place the returned HTML into the matched element.
   *
   * The url allows us to specify a portion of the remote document to be inserted. This is achieved
   * with a special syntax for the url parameter. If one or more space characters are included in
   * the string, the portion of the string following the first space is assumed to be a GQuery
   * selector that determines the content to be loaded.
   *
   */
  public GQuery load(String url, IsProperties data, final Function onSuccess) {
    return as(Ajax.Ajax).load(url, data, onSuccess);
  }

  /**
   * Reduce the set of matched elements to all elements before a given position. The position of the
   * element in the set of matched elements starts at 0 and goes to length - 1.
   */
  public GQuery lt(int pos) {
    return slice(0, pos);
  }

  /**
   * Pass each element in the current matched set through a function, producing a new array
   * containing the return values. When the call to the function returns a null it is not added to
   * the array.
   */
  public <W> List<W> map(Function f) {
    ArrayList<W> ret = new ArrayList<W>();
    int i = 0;
    for (Element e : elements) {
      @SuppressWarnings("unchecked")
      W o = (W) f.f(e.<com.google.gwt.dom.client.Element> cast(), i++);
      if (o != null) {
        ret.add(o);
      }
    }
    return ret;
  }

  /**
   * Bind a set of functions to the mousedown event of each matched element. Or trigger the event if
   * no functions are provided.
   */
  public GQuery mousedown(Function... f) {
    return bindOrFire(Event.ONMOUSEDOWN, null, f);
  }

  /**
   * Bind an event handler to be fired when the mouse enter an element, or trigger that handler on
   * an element if no functions are provided.
   *
   * The mouseenter event differs from mouseover in the way it handles event bubbling. When
   * mouseover is used on an element having inner element(s), then when the mouse pointer moves hover
   * of the Inner element, the handler would be triggered. This is usually undesirable behavior. The
   * mouseenter event, on the other hand, only triggers its handler when the mouse enters the
   * element it is bound to, not a descendant.
   */
  public GQuery mouseenter(Function... f) {
    return as(Events).mouseenter(f);
  }

  /**
   * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on
   * an element if no functions are provided.
   *
   * The mouseleave event differs from mouseout in the way it handles event bubbling. When
   * mouseout is used on an element having inner element(s), then when the mouse pointer moves out
   * of the Inner element, the handler would be triggered. This is usually undesirable behavior. The
   * mouseleave event, on the other hand, only triggers its handler when the mouse leaves the
   * element it is bound to, not a descendant.
   */
  public GQuery mouseleave(Function... f) {
    return as(Events).mouseleave(f);
  }

  /**
   * Bind a set of functions to the mousemove event of each matched element. Or trigger the event if
   * no functions are provided.
   */
  public GQuery mousemove(Function... f) {
    return bindOrFire(Event.ONMOUSEMOVE, null, f);
  }

  /**
   * Bind a set of functions to the mouseout event of each matched element. Or trigger the event if
   * no functions are provided.
   */
  public GQuery mouseout(Function... f) {
    return bindOrFire(Event.ONMOUSEOUT, null, f);
  }

  /**
   * Bind a set of functions to the mouseover event of each matched element. Or trigger the event if
   * no functions are provided.
   */
  public GQuery mouseover(Function... f) {
    return bindOrFire(Event.ONMOUSEOVER, null, f);
  }

  /**
   * Bind a set of functions to the mouseup event of each matched element. Or trigger the event if
   * no functions are provided.
   */
  public GQuery mouseup(Function... f) {
    return bindOrFire(Event.ONMOUSEUP, null, f);
  }

  /**
   * Get a set of elements containing the unique next siblings of each of the given set of elements.
   * next only returns the very next sibling for each element, not all next siblings see {#nextAll}.
   */
  public GQuery next() {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      Element next = e.getNextSiblingElement();
      if (next != null) {
        result.addNode(next);
      }
    }
    return pushStack(unique(result), "next", getSelector());
  }

  /**
   * Get a set of elements containing the unique next siblings of each of the given set of elements
   * filtered by 1 or more selectors. next only returns the very next sibling for each element, not
   * all next siblings see {#nextAll}.
   */
  public GQuery next(String... selectors) {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      Element next = e.getNextSiblingElement();
      if (next != null) {
        result.addNode(next);
      }
    }
    return pushStack(result, "next", selectors[0]).filter(selectors);
  }

  /**
   * Get all following siblings of each element in the set of matched elements.
   */
  public GQuery nextAll() {
    return nextAll(null);
  }

  /**
   * Get all following siblings of each element in the set of matched elements, filtered by a
   * selector.
   */
  public GQuery nextAll(String filter) {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      allNextSiblingElements(e.getNextSiblingElement(), result, null, null, filter);
    }

    return pushStack(unique(result), "nextAll", getSelector());
  }

  /**
   * Get all following siblings of each element up to but not including the element matched by the
   * selector.
   *
   * @param selector
   * @return
   */
  public GQuery nextUntil(String selector) {
    return nextUntil($(selector), null);
  }

  /**
   * Get all following siblings of each element up to but not including the element matched by the
   * selector, filtered by a selector.
   *
   * @param selector
   * @return
   */
  public GQuery nextUntil(String selector, String filter) {
    return nextUntil($(selector), filter);
  }

  /**
   * Get all following siblings of each element up to but not including the element matched by the
   * DOM node.
   *
   * @param selector
   * @return
   */
  public GQuery nextUntil(Element until) {
    return nextUntil($(until), null);
  }

  /**
   * Get all following siblings of each element up to but not including the element matched by the
   * DOM node, filtered by a selector.
   *
   * @return
   */
  public GQuery nextUntil(Element until, String filter) {
    return nextUntil($(until), filter);
  }

  /**
   * Get all following siblings of each element up to but not including the element matched by the
   * GQuery object.
   *
   * @return
   */
  public GQuery nextUntil(GQuery until) {
    return nextUntil(until, null);
  }

  /**
   * Get all following siblings of each element up to but not including the element matched by the
   * GQuery object, filtered by a selector.
   *
   * @return
   */
  public GQuery nextUntil(GQuery until, String filter) {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      allNextSiblingElements(e.getNextSiblingElement(), result, null, until, filter);
    }
    return pushStack(unique(result), "nextUntil", getSelector());
  }

  /**
   * Removes the specified Element from the set of matched elements. This method is used to remove a
   * single Element from a jQuery object.
   */
  public GQuery not(Element elem) {
    JsNodeArray array = JsNodeArray.create();
    for (Element e : elements) {
      if (e != elem) {
        array.addNode(e);
      }
    }
    return $(array);
  }

  /**
   * Removes any elements inside the passed set of elements from the set of matched elements.
   */
  public GQuery not(GQuery gq) {
    GQuery ret = this;
    for (Element e : gq.elements) {
      ret = ret.not(e);
    }
    return ret;
  }

  /**
   * Removes elements matching the specified expression from the set of matched elements.
   */
  public GQuery not(String... filters) {
    GQuery ret = this;
    for (String f : filters) {
      ret = ret.not($(f));
    }
    return ret;
  }

  /**
   * Get the current offset of the first matched element, in pixels, relative to the document. The
   * returned object contains two integer properties, top and left. The method works only with
   * visible elements.
   */
  public Offset offset() {
    Element e = get(0);
    return e == null ? new Offset(0, 0) : new Offset(e.getAbsoluteLeft(), e.getAbsoluteTop());
  }

  /**
   * Set the current coordinates of every element in the set of matched elements, relative to the document.
   */
  public GQuery offset(Offset offset) {
    assert offset() != null : "offset cannot be null";
    return offset(offset.top, offset.left);
  }

  /**
   * Set the current coordinates of every element in the set of matched elements, relative to the document.
   */
  public GQuery offset(int top, int left) {
    for (Element element : elements()) {
      GQuery g = $(element);

      String position = g.css("position", true);
      if ("static".equals(position)) {
        css("position", "relative");
      }

      Offset curOffset = g.offset();
      String curCSSTop = g.css("top", true);
      String curCSSLeft = g.css("left", true);
      long curTop = 0;
      long curLeft = 0;

      if (("absolute".equals(position) || "fixed".equals(position))
          && ("auto".equals(curCSSTop) || "auto".equals(curCSSLeft))) {
        Offset curPosition = g.position();
        curTop = curPosition.top;
        curLeft = curPosition.left;
      } else {
        try {
          curTop = Long.parseLong(curCSSTop);
        } catch (NumberFormatException e) {
          curTop = 0;
        }

        try {
          curLeft = Long.parseLong(curCSSLeft);
        } catch (NumberFormatException e) {
          curLeft = 0;
        }
      }

      long newTop = top - curOffset.top + curTop;
      long newLeft = left - curOffset.left + curLeft;

      g.css("top", "" + newTop).css("left", "" + newLeft);
    }

    return this;
  }

  /**
   * Returns a GQuery collection with the positioned parent of the first matched element. This is
   * the first parent of the element that has position (as in relative or absolute). This method
   * only works with visible elements.
   */
  public GQuery offsetParent() {
    if (isEmpty()) {
      return $();
    }
    Element offParent = JsUtils.or(get(0).getOffsetParent(), body);
    while (offParent != null && !"body".equalsIgnoreCase(offParent.getTagName())
        && !"html".equalsIgnoreCase(offParent.getTagName())
        && "static".equals(getStyleImpl().curCSS(offParent, "position", true))) {
      offParent = offParent.getOffsetParent();
    }
    return new GQuery(offParent);
  }

  /**
   * Attach an event handler function for one or more events to the selected elements.
   */
  public GQuery on(String eventName, Function... funcs) {
    return bind(eventName, funcs);
  }

  /**
   * Attach an event handler function for one or more events to the selected elements.
   */
  public GQuery on(String eventName, Object data, Function... funcs) {
    return bind(eventName, data, funcs);
  }

  /**
   * Attach an event handler function for one or more events to the selected elements.
   */
  public GQuery on(String eventName, String selector, Function... funcs) {
    if (selector == null || selector.isEmpty()) {
      return on(eventName, funcs);
    }

    return delegate(selector, eventName, funcs);
  }

  /**
   * Attach an event handler function for one or more events to the selected elements.
   */
  public GQuery on(String eventName, String selector, Object data, Function... funcs) {
    if (selector == null || selector.isEmpty()) {
      return on(eventName, data, funcs);
    }

    return delegate(selector, eventName, data, funcs);
  }

  /**
   * Remove all event handlers.
   */
  public GQuery off() {
    return as(Events).off();
  }

  /**
   * Remove an event handler.
   */
  public GQuery off(String eventName) {
    return unbind(eventName, null);
  }

  /**
   * Remove an event handler.
   */
  public GQuery off(String eventName, Function f) {
    return unbind(eventName, f);
  }

  /**
   * Remove an event handler.
   */
  public GQuery off(String eventName, String selector) {
    if (selector == null || selector.isEmpty()) {
      return off(eventName);
    }
    return undelegate(selector, eventName);
  }

  /**
   * Binds a handler to a particular Event (like Event.ONCLICK) for each matched element. The
   * handler is executed only once for each element.
   *
   * The event handler is passed as a Function that you can use to prevent default behavior. To stop
   * both default action and event bubbling, the function event handler has to return false.
   *
   * You can pass an additional Object data to your Function as the second parameter
   */
  public GQuery one(int eventbits, final Object data, final Function f) {
    return as(Events).one(eventbits, data, f);
  }

  /**
   * Get the current computed height for the first element in the set of matched elements, including
   * padding, border, but not the margin.
   */
  public int outerHeight() {
    return outerHeight(false);
  }

  /**
   * Get the current computed height for the first element in the set of matched elements, including
   * padding, border, and optionally margin.
   */
  public int outerHeight(boolean includeMargin) {
    if (isEmpty()) {
      return 0;
    }
    // height including padding and border
    int outerHeight = (int) cur("offsetHeight", true);
    if (includeMargin) {
      outerHeight += cur("marginTop", true) + cur("marginBottom", true);
    }
    return outerHeight;
  }

  /**
   * Get the current computed width for the first element in the set of matched elements, including
   * padding, border, but not the margin.
   */
  public int outerWidth() {
    return outerWidth(false);
  }

  /**
   * Get the current computed width for the first element in the set of matched elements, including
   * padding and border and optionally margin.
   */
  public int outerWidth(boolean includeMargin) {
    if (isEmpty()) {
      return 0;
    }
    // width including padding and border
    int outerWidth = (int) cur("offsetWidth", true);
    if (includeMargin) {
      outerWidth += cur("marginRight", true) + cur("marginLeft", true);
    }
    return outerWidth;
  }

  /**
   * Get a set of elements containing the unique parents of the matched set of elements.
   */
  public GQuery parent() {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      Element p = e.getParentElement();
      if (p != null) {
        result.addNode(p);
      }
    }
    return new GQuery(unique(result));
  }

  /**
   * Get a set of elements containing the unique parents of the matched set of elements. You may use
   * an optional expressions to filter the set of parent elements that will match one of them.
   */
  public GQuery parent(String... filters) {
    return parent().filter(filters);
  }

  /**
   * Get a set of elements containing the unique ancestors of the matched set of elements (except
   * for the root element).
   */
  public GQuery parents() {
    return parentsUntil((String) null);
  }

  /**
   * Get a set of elements containing the unique ancestors of the matched set of elements (except
   * for the root element). The matched elements are filtered, returning those that match any of the
   * filters.
   */
  public GQuery parents(String... filters) {
    return parents().filter(filters);
  }

  /**
   * Get the ancestors of each element in the current set of matched elements, up to but not
   * including the element matched by the selector.
   */
  public GQuery parentsUntil(final String selector) {
    return parentsUntil(new Predicate() {
      @Override
      public <T> boolean f(T e, int index) {
        return selector != null && $(e).is(selector);
      }
    });
  }

  /**
   * Get the ancestors of each element in the current set of matched elements, up to but not
   * including the node.
   */
  public GQuery parentsUntil(final Node node) {
    return parentsUntil(new Predicate() {
      @Override
      public <T> boolean f(T e, int index) {
        return node != null && e == node;
      }
    });
  }

  private GQuery parentsUntil(Predicate predicate) {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      int i = 0;
      Node par = e.getParentNode();
      while (par != null && par != document) {
        if (predicate.f(par, i)) {
          break;
        }
        result.addNode(par);
        par = par.getParentNode();
        i++;
      }
    }
    return new GQuery(unique(result)).setPreviousObject(this);
  }

  /**
   * Gets the top and left position of an element relative to its offset parent. The returned object
   * contains two Integer properties, top and left. For accurate calculations make sure to use pixel
   * values for margins, borders and padding. This method only works with visible elements.
   */
  public Offset position() {
    if (isEmpty()) {
      return new Offset(0, 0);
    }
    Element element = get(0);
    // Get *real* offsetParent
    Element offsetParent = get(0).getOffsetParent();
    // Get correct offsets
    Offset offset = offset();
    Offset parentOffset = null;
    if (offsetParent == body || offsetParent == (Node) document) {
      parentOffset = new Offset(0, 0);
    } else {
      parentOffset = $(offsetParent).offset();
    }

    // Subtract element margins
    int topMargin = (int) getStyleImpl().cur(element, "marginTop", true);
    // TODO: move this check to getStyleImpl()
    // When margin-left = auto, Safari and chrome return a value while IE and
    // Firefox return 0
    // force the margin-left to 0 if margin-left = auto.
    int leftMargin = 0;
    if (!"auto".equals(element.getStyle().getMarginLeft())) {
      leftMargin = (int) getStyleImpl().cur(element, "marginLeft", true);
    }

    offset = offset.add(-leftMargin, -topMargin);

    // Add offsetParent borders
    int parentOffsetBorderTop = (int) getStyleImpl().cur(offsetParent, "borderTopWidth", true);
    int parentOffsetBorderLeft = (int) getStyleImpl().cur(offsetParent, "borderLeftWidth", true);
    parentOffset = parentOffset.add(parentOffsetBorderLeft, parentOffsetBorderTop);

    // Subtract the two offsets
    return offset.add(-parentOffset.left, -parentOffset.top);
  }

  /**
   * Prepend content to the inside of every matched element. This operation is the best way to
   * insert elements inside, at the beginning, of all matched elements.
   */
  public GQuery prepend(GQuery query) {
    return domManip(query, DomMan.PREPEND);
  }

  /**
   * Prepend content to the inside of every matched element. This operation is the best way to
   * insert elements inside, at the beginning, of all matched elements.
   */
  public GQuery prepend(Node n) {
    return domManip($(n), DomMan.PREPEND);
  }

  /**
   * Prepend content to the inside of every matched element. This operation is the best way to
   * insert elements inside, at the beginning, of all matched elements.
   */
  public GQuery prepend(String html) {
    return domManip(html, DomMan.PREPEND);
  }

  /**
   * All of the matched set of elements will be inserted at the beginning of the element(s)
   * specified by the parameter other.
   *
   * The operation $(A).prependTo(B) is, essentially, the reverse of doing a regular
   * $(A).prepend(B), instead of prepending B to A, you're prepending A to B.
   */
  public GQuery prependTo(GQuery other) {
    other.prepend(this);
    return this;
  }

  /**
   * All of the matched set of elements will be inserted at the beginning of the element(s)
   * specified by the parameter other.
   *
   * The operation $(A).prependTo(B) is, essentially, the reverse of doing a regular
   * $(A).prepend(B), instead of prepending B to A, you're prepending A to B.
   */
  public GQuery prependTo(Node n) {
    $(n).prepend(this);
    return this;
  }

  /**
   * All of the matched set of elements will be inserted at the beginning of the element(s)
   * specified by the parameter other.
   *
   * The operation $(A).prependTo(B) is, essentially, the reverse of doing a regular
   * $(A).prepend(B), instead of prepending B to A, you're prepending A to B.
   */
  public GQuery prependTo(String html) {
    $(html).prepend(this);
    return this;
  }

  /**
   * Get a set of elements containing the unique previous siblings of each of the matched set of
   * elements. Only the immediately previous sibling is returned, not all previous siblings.
   */
  public GQuery prev() {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      Element next = getPreviousSiblingElement(e);
      if (next != null) {
        result.addNode(next);
      }
    }
    return new GQuery(unique(result));
  }

  /**
   * Get a set of elements containing the unique previous siblings of each of the matched set of
   * elements filtered by selector. Only the immediately previous sibling is returned, not all
   * previous siblings.
   */
  public GQuery prev(String... selectors) {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      Element next = getPreviousSiblingElement(e);
      if (next != null) {
        result.addNode(next);
      }
    }
    return new GQuery(unique(result)).filter(selectors);
  }

  /**
   * Get all preceding siblings of each element in the set of matched elements.
   */
  public GQuery prevAll() {
    return prevAll(null);
  }

  /**
   * Get all preceding siblings of each element in the set of matched elements filtered by a
   * selector.
   */
  public GQuery prevAll(String selector) {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      allPreviousSiblingElements(getPreviousSiblingElement(e), result, null, selector);
    }
    return pushStack(unique(result), "prevAll", getSelector());
  }

  /**
   * Get all preceding siblings of each element up to but not including the element matched by the
   * <code>selector</code>.
   *
   * The elements are returned in order from the closest sibling to the farthest.
   */
  public GQuery prevUntil(String selector) {
    return prevUntil($(selector), null);
  }

  /**
   * Get all preceding siblings of each element up to but not including the <code>until</code>
   * element.
   *
   * The elements are returned in order from the closest sibling to the farthest.
   */
  public GQuery prevUntil(Element until) {
    return prevUntil($(until), null);
  }

  /**
   * Get all preceding siblings of each element up to but not including the <code>until</code>
   * element.
   *
   * The elements are returned in order from the closest sibling to the farthest.
   */
  public GQuery prevUntil(GQuery until) {
    return prevUntil(until, null);
  }

  /**
   * Get all preceding siblings of each element matching the <code>filter</code> up to but not
   * including the element matched by the <code>selector</code>.
   *
   * The elements are returned in order from the closest sibling to the farthest.
   */
  public GQuery prevUntil(String selector, String filter) {
    return prevUntil($(selector), filter);
  }

  /**
   * Get all preceding siblings of each element matching the <code>filter</code> up to but not
   * including the <code>until</code> element.
   *
   */
  public GQuery prevUntil(Element until, String filter) {
    return prevUntil($(until), filter);
  }

  /**
   * Get all preceding siblings of each element matching the <code>filter</code> up to but not
   * including the element matched by the <code>until</code> element.
   *
   */
  public GQuery prevUntil(GQuery until, String filter) {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      allPreviousSiblingElements(getPreviousSiblingElement(e), result, until, filter);
    }
    return pushStack(unique(result), "prevUntil", getSelector());
  }

  /**
   * Returns a dynamically generated Promise that is resolved once all actions
   * in the queue have ended.
   */
  public Promise promise() {
    return as(Queue).promise();
  }

  /**
   * Returns a dynamically generated Promise that is resolved once all actions
   * in the named queue have ended.
   */
  public Promise promise(String name) {
    return as(Queue).promise(name);
  }

  /**
   * Get the value of a property for the first element in the set of matched elements.
   *
   * @param key the name of the property to be accessed
   * @return the value of the property, in the case the property is a 'boolean' it
   *        returns a Boolean object, and a Double if is a 'number', so be prepared
   *        if you cast to other numeric objects. In the case of the property is undefined
   *        it returns null.
   */
  public <T> T prop(String key) {
    assert key != null : "Key is null";
    return isEmpty() ? null : JsUtils.<T> prop(get(0), key);
  }

  /**
   * Get the value of a property for the first element in the set of matched elements.
   *
   * @param key the name of the property to be accessed
   * @param clz the class of the type to return
   *
   * @return the value of the property, it safely check the type passed as parameter
   *        and preform the aproproate transformations for numbers and booleans.
   *        In the case of the property is undefined it returns null.
   */
  public <T> T prop(String key, Class<? extends T> clz) {
    assert key != null : "Key is null";
    return isEmpty() ? null : JsUtils.<T> prop(get(0), key, clz);
  }

  /**
   * Sets a property to a value on all matched elements.
   *
   * @param key the name of the boolean property to be set
   * @param value the value specified. In the case the value is a Number, it is set
   *        as a 'number' in the javascript object and the same with Boolean.
   *
   * @return this <code>GQuery</code> object
   *
   */
  public GQuery prop(String key, Object value) {
    assert key != null : "Key is null";

    for (Element e : elements) {
      JsUtils.prop(e, key, value);
    }

    return this;
  }

  /**
   * Sets a boolean property to a computed value on all matched elements.
   *
   * @param key the name of the boolean property to be set
   * @param closure the closure to be used to compute the value the specified boolean property
   *          should be set to; the <code>closure</code> is
   *          {@linkplain Function#f(com.google.gwt.dom.client.Element, int) passed} the target
   *          element and its index as arguments and is expected to return either a
   *          <code>Boolean</code> value or an object whose textual representation is converted to a
   *          <code>Boolean</code> value; <code>null</code> return values are ignored
   *
   * @return this <code>GQuery</code> object
   *
   */
  public GQuery prop(String key, Function closure) {
    assert key != null : "Key is null";
    assert closure != null : "Closure is null";

    int i = 0;
    for (Element e : elements) {
      Object value = closure.f(e, i++);
      JsUtils.prop(e, key, value);
    }

    return this;
  }

  protected GQuery pushStack(JsNodeArray elts, String name, String selector) {
    GQuery g = new GQuery(elts);
    g.setPreviousObject(this);
    g.setSelector(selector);
    g.currentContext = currentContext;
    return g;
  }

  /**
   * Show the number of functions in the efects queue to be executed on the first matched element.
   */
  public int queue() {
    return as(Queue).queue();
  }

  /**
   * Put a set of {@link Function} at the end of the Effects queue.
   *
   * Example:
   *
   * <pre class="code">
   * $("#foo").animate("left:'+=500'", 400)
   *      .queue(new Function(){
   *          public void f(Element e){
   *             $(e).css(CSS.BACKGROUNG_COLOR.with(RGBColor.RED));
   *             $(e).dequeue();
   *          }
   *        })
   *       .animate("left:'-=500'", 400)
   *       .queue(lazy().css("color", "yellow");
   *
   * </pre>
   *
   * When this statement is executed, the element move to 500 px to left for 400 ms, then its
   * background color is changed to red and then move to 500px to right for 400ms, and finally its
   * color is set to yellow.
   *
   * Please note that {@link #dequeue()} function is needed at the end of your function to start the
   * next function in the queue. In lazy() methods you should call dequeue() just before the done()
   * call. {@see #dequeue()}
   */
  public GQuery queue(Function... f) {
    return as(Queue).queue(f);
  }

  /**
   * Show the number of functions in the queued named as queueName to be executed on the first
   * matched element.
   */
  public int queue(String queueName) {
    return as(Queue).queue(queueName);
  }

  /**
   * Put a set of {@link Function} at the end of a queue.
   *
   * Example:
   *
   * <pre class="code">
   * $("#foo").queue("myQueue", new Function(){
   *          public void f(Element e){
   *             $(e).css(CSS.BACKGROUNG_COLOR.with(RGBColor.RED));
   *             dequeue("myQueue");
   *          }
   *        })
   *        .delay(500, "myQueue")
   *        .queue("myQueue", lazy().css(CSS.COLOR.with(RGBColor.YELLOW)).dequeue("myQueue").done());
   * </pre>
   *
   * When this statement is executed, the background color of the element is set to red, then wait
   * 500ms before to set the text color of the element to yellow. right for 400ms.
   *
   * Please note that {@link #dequeue()} function is needed at the end of your function to start the
   * next function in the queue. In lazy() methods you should call dequeue() just before the done()
   * call. {@see #dequeue()}
   */
  public GQuery queue(String queueName, Function... f) {
    return as(Queue).queue(queueName, f);
  }

  /**
   * Specify a function to execute when the DOM is fully loaded.
   *
   * While JavaScript provides the load event for executing code when a page is rendered, this event
   * is not seen if we attach an event listener after the document has been loaded.
   * This guarantees that our gwt code will be executed either it's executed synchronously before the
   * DOM has been rendered (ie: single script linker in header) or asynchronously.
   */
  public Promise ready(Function... fncs) {
    return new PromiseFunction() {
      public void f(final com.google.gwt.query.client.Promise.Deferred dfd) {
        if ("complete" == $(document).prop("readyState")) {
          dfd.resolve();
        } else {
          $(document).on("load", new Function() {
            public void f() {
              dfd.resolve();
            }
          });
        }
      }
    }.done(fncs);
  }

  /**
   * Removes all matched elements from the DOM.
   */
  public GQuery remove() {
    return remove(null, true);
  }

  /**
   * Removes from the DOM all matched elements filtered by the <code>filter</code>.
   */
  public GQuery remove(String filter) {
    return remove(filter, true);
  }

  /**
   * Removes all matched elements from the DOM and cleans their data and bound events if the value
   * of <code>clean</code> parameter is set to true. The <code> filter</code> parameter allows to
   * filter the matched set to remove.
   */
  protected GQuery remove(String filter, boolean clean) {
    for (Element e : elements) {
      if (filter == null || $(e).filter(filter).length() == 1) {
        if (clean) {
          // clean data linked to the children
          // TODO: "*" fails in queryselectorall (webkit mobile)
          cleanGQData($("*", e).elements());
          // clean data linked to the element itself
          cleanGQData(e);
        }
        Widget w = getAssociatedWidget(e);
        if (w != null) {
          w.removeFromParent();
        } else {
          e.removeFromParent();
        }
      }
    }
    return this;
  }

  /**
   * Remove the named attribute from every element in the matched set.
   */
  public GQuery removeAttr(String key) {
    getAttributeImpl().removeAttribute(this, key);
    return this;
  }

  /**
   * Removes the specified classes to each matched element.
   *
   * If no arguments are provided, it removes all classes like jquery does.
   */
  public GQuery removeClass(String... classes) {
    for (Element e : elements) {
      if (Element.is(e)) {
        if (classes.length == 0) {
          e.setClassName(null);
        } else {
          for (String clz : classes) {
            e.removeClassName(clz);
          }
        }
      }
    }
    return this;
  }

  protected void removeData(Element item, String name) {
    if (dataCache == null) {
      windowData = JavaScriptObject.createObject().cast();
      dataCache = JavaScriptObject.createObject().cast();
    }
    item = item == window || item.getNodeName() == null ? windowData : item;
    int id = item.hashCode();
    if (name != null) {
      if (dataCache.exists(id)) {
        dataCache.getCache(id).delete(name);
        if (dataCache.getCache(id).isEmpty()) {
          // Save memory
          removeData(item, null);
        }
      }
    } else {
      // when the element cache is empty we remove its entry to save memory (issue 132)
      dataCache.delete(id);
    }
  }

  /**
   * Removes named data store from an element.
   */
  public GQuery removeData(String name) {
    for (Element e : elements) {
      removeData(e, name);
    }
    return this;
  }

  /**
   * Remove a property for the set of matched elements.
   */
  public GQuery removeProp(String name) {
    for (Element e : elements) {
      e.<JsCache> cast().delete(name);
    }
    return this;
  }

  /**
   * Replaces the element <code>elem</code> by the specified selector with the matched elements.
   * This function is the complement to replaceWith() which does the same task with the parameters
   * reversed.
   *
   * @return a {@link GQuery} object containing the new elements.
   */
  public GQuery replaceAll(Element elem) {
    return replaceAll($(elem));
  }

  /**
   * Replaces the elements matched by the target with the selected elements. This function is the
   * complement to replaceWith() which does the same task with the parameters reversed.
   *
   * @return a {@link GQuery} object containing the new elements.
   */
  public GQuery replaceAll(GQuery target) {
    // if there is only one element and it is not attached to the dom, we have
    // to clone it to be reused on each element of target (if target contains
    // more than one element)
    boolean mustBeCloned = length() == 1 && parents().filter("body").length() == 0;

    List<Element> newElements = new ArrayList<Element>();
    for (int i = 0, l = target.size(); i < l; i++) {
      GQuery that = (i > 0 && mustBeCloned) ? this.clone() : this;
      $(target.get(i)).replaceWith(that);
      newElements.addAll(Arrays.asList(that.elements));
    }
    return $(newElements);
  }

  /**
   * Replaces the elements matched by the specified selector with the matched elements. This
   * function is the complement to replaceWith() which does the same task with the parameters
   * reversed.
   *
   * @return a {@link GQuery} object containing the new elements.
   */
  public GQuery replaceAll(String selector) {
    return replaceAll($(selector));
  }

  /**
   * Replaces all matched elements with the specified element.
   *
   * @return the GQuery element that was just replaced, which has been removed from the DOM and not
   *         the new element that has replaced it.
   */
  public GQuery replaceWith(Element elem) {
    return replaceWith($(elem));
  }

  /**
   * Replaces all matched elements with elements selected by <code>target</code> .
   *
   * @return the GQuery element that was just replaced, which has been removed from the DOM and not
   *         the new element that has replaced it.
   */
  public GQuery replaceWith(GQuery target) {
    for (Element el : elements) {
      Element nextSibling = el.getNextSiblingElement();

      if (nextSibling != null) {
        $(nextSibling).before(target);
      } else {
        Element parent = el.getParentElement();
        $(parent).append(target);
      }
      $(el).remove();
    }
    return this;
  }

  /**
   * Replaces all matched elements with the specified HTML.
   *
   * @return the GQuery element that was just replaced, which has been removed from the DOM and not
   *         the new element that has replaced it.
   */
  public GQuery replaceWith(String html) {
    for (Element el : elements) {
      Element nextSibling = el.getNextSiblingElement();

      if (nextSibling != null) {
        $(nextSibling).before(html);
      } else {
        Element parent = el.getParentElement();
        $(parent).append(html);
      }
      $(el).remove();
    }
    return this;
  }

  /**
   * Bind a set of functions to the resize event of each matched element, or tigger the resize event
   * if no functions are provided.
   *
   * Note that although all elements can be configured to handle resize events, by default only
   * window will trigger it when it is resized, for an arbitrary element you have to trigger the
   * event after resizing the object.
   *
   */
  public GQuery resize(Function... f) {
    return bindOrFire("resize", null, f);
  }

  /**
   * Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.
   */
  public GQuery resize(final Function f) {
    return bindOrFire("resize", null, f);
  }

  /**
   * Save a set of Css properties of every matched element.
   */
  public void restoreCssAttrs(String... cssProps) {
    for (Element e : elements) {
      for (String a : cssProps) {
        String datakey = OLD_DATA_PREFIX + a;
        getStyleImpl().setStyleProperty(e, a, (String) data(e, datakey, null));
        removeData(e, datakey);
      }
    }
  }

  /**
   * Restore a set of previously saved Css properties in every matched element.
   */
  public void saveCssAttrs(String... cssProps) {
    for (Element e : elements) {
      for (String a : cssProps) {
        data(OLD_DATA_PREFIX + a, getStyleImpl().curCSS(e, a, false));
      }
    }
  }

  /**
   * Bind a set of functions to the scroll event of each matched element. Or trigger the event if no
   * functions are provided.
   */
  public GQuery scroll(Function... f) {
    return bindOrFire(Event.ONSCROLL, null, f);
  }

  /**
   * Scrolls the first matched element into view.
   */
  public GQuery scrollIntoView() {
    if (!isEmpty()) {
      scrollIntoViewImpl(get(0));
    }
    return this;
  }

  /**
   * Scrolls the first matched element into view.
   *
   * If ensure == true, it crawls up the DOM hierarchy, adjusting the scrollLeft and scrollTop
   * properties of each scroll-able element to ensure that the specified element is completely in
   * view. It adjusts each scroll position by the minimum amount necessary.
   */
  public GQuery scrollIntoView(boolean ensure) {
    if (!isEmpty() && ensure) {
      DOM.scrollIntoView((com.google.gwt.user.client.Element) get(0));
    } else {
      scrollIntoView();
    }
    return this;
  }

  /**
   * Gets the scroll left offset of the first matched element. This method works for both visible
   * and hidden elements.
   */
  public int scrollLeft() {
    Element e = get(0);
    if (e == null) {
      return 0;
    }
    if (e == window || e.getNodeName() == null) {
      return Window.getScrollLeft();
    } else if (e == (Node) document) {
      return document.getScrollLeft();
    } else {
      return e.getScrollLeft();
    }
  }

  /**
   * The scroll left offset is set to the passed value on all matched elements. This method works
   * for both visible and hidden elements.
   */
  public GQuery scrollLeft(int left) {
    for (Element e : elements) {
      if (e == window || e.getNodeName() == null || e == (Node) document) {
        Window.scrollTo(left, $(e).scrollTop());
      } else {
        e.setPropertyInt("scrollLeft", left);
      }
    }
    return this;
  }

  /**
   *
   * Scrolls the contents of all matched elements to the specified co-ordinate becoming the top left
   * corner of the viewable area.
   *
   * This method is only useful where there are areas of the document not viewable within the
   * current viewable area of the window and the visible property of the window's scrollbar must be
   * set to true.
   *
   */
  public GQuery scrollTo(int left, int top) {
    scrollLeft(left).scrollTop(top);
    return this;
  }

  /**
   * Gets the scroll top offset of the first matched element. This method works for both visible and
   * hidden elements.
   */
  public int scrollTop() {
    Element e = get(0);
    if (e == null) {
      return 0;
    }
    if (e == window || e.getNodeName() == null) {
      return Window.getScrollTop();
    } else if (e == (Node) document) {
      return document.getScrollTop();
    } else {
      return e.getScrollTop();
    }
  }

  /**
   * The scroll top offset is set to the passed value on all matched elements. This method works for
   * both visible and hidden elements.
   */
  public GQuery scrollTop(int top) {
    for (Element e : elements) {
      if (e == window || e.getNodeName() == null || e == (Node) document) {
        Window.scrollTo($(e).scrollLeft(), top);
      } else {
        e.setPropertyInt("scrollTop", top);
      }
    }
    return this;
  }

  public GQuery select() {
    return as(Events).triggerHtmlEvent("select");
  }

  private GQuery select(String selector, Node context) {
    NodeList<Element> n = getSelectorEngine().select(selector, context == null ? document :
        context);
    currentSelector = selector;
    currentContext = context != null ? context : document;
    return setArray(n);
  }

  /**
   * Force the current matched set of elements to become the specified array of elements.
   */
  public GQuery setArray(NodeList<Element> list) {
    if (list != null) {
      nodeList.<JsCache> cast().clear();
      int l = list.getLength();
      elements = new Element[l];
      for (int i = 0; i < l; i++) {
        elements[i] = list.getItem(i);
        nodeList.<JsObjectArray<Element>> cast().add(list.getItem(i));
      }
    }
    return this;
  }

  public GQuery setPreviousObject(GQuery previousObject) {
    this.previousObject = previousObject;
    return this;
  }

  public GQuery setSelector(String selector) {
    this.currentSelector = selector;
    return this;
  }

  /**
   * Make all matched elements visible.
   */
  public GQuery show() {
    for (Element e : elements) {
      String currentDisplay = e.getStyle().getDisplay();
      String oldDisplay = (String) data(e, OLD_DISPLAY, null);

      // reset the display
      if (oldDisplay == null && "none".equals(currentDisplay)) {
        getStyleImpl().setStyleProperty(e, "display", "");
        currentDisplay = "";
      }

      // check if the stylesheet impose display: none. If it is the case, determine
      // the default display for the tag and store it at the element level
      if ("".equals(currentDisplay) && !getStyleImpl().isVisible(e)) {
        data(e, OLD_DISPLAY, getStyleImpl().defaultDisplay(e.getNodeName()));
      }
    }

    // set the display value in a separate for loop to avoid constant reflow
    // because broswer reflow is triggered each time we gonna set and after get (in
    // isVisibleProperty() method)
    // the diplay property. Reflows is very bad in performance point of view
    for (Element e : elements) {
      String currentDisplay = e.getStyle().getDisplay();
      if ("".equals(currentDisplay) || "none".equals(currentDisplay)) {
        getStyleImpl().setStyleProperty(e, "display",
            JsUtils.or((String) data(e, OLD_DISPLAY, null), ""));
      }
    }
    removeData(OLD_DISPLAY);
    return this;
  }

  /**
   * Get a set of elements containing all of the unique siblings of each of the matched set of
   * elements.
   */
  public GQuery siblings() {
    JsNodeArray result = JsNodeArray.create();
    for (Element e : elements) {
      allNextSiblingElements(e.getParentElement().getFirstChildElement(), result, e, null, null);
    }
    return new GQuery(unique(result));
  }

  /**
   * Get a set of elements containing all of the unique siblings of each of the matched set of
   * elements filtered by the provided set of selectors.
   */
  public GQuery siblings(String... selectors) {
    return siblings().filter(selectors);
  }

  /**
   * Return the number of elements in the matched set.
   */
  public int size() {
    return elements.length;
  }

  /**
   * Selects a subset of the matched elements.
   */
  public GQuery slice(int start, int end) {
    JsNodeArray slice = JsNodeArray.create();
    int l = size();
    if (end == -1 || end > l) {
      end = l;
    }
    for (int i = start; i < end; i++) {
      slice.addNode(get(i));
    }
    return new GQuery(slice);
  }

  /**
   * Reveal all matched elements by adjusting their height and firing an optional callback after
   * completion.
   */
  public Effects slideDown(Function... f) {
    return as(Effects).slideDown(f);
  }

  /**
   * Reveal all matched elements by adjusting their height and firing an optional callback after
   * completion.
   */
  public Effects slideDown(int millisecs, Function... f) {
    return as(Effects).slideDown(millisecs, f);
  }

  /**
   * Toggle the visibility of all matched elements by adjusting their height and firing an optional
   * callback after completion. Only the height is adjusted for this animation, causing all matched
   * elements to be hidden or shown in a "sliding" manner
   */
  public Effects slideToggle(Function... f) {
    return as(Effects).slideToggle(f);
  }

  /**
   * Toggle the visibility of all matched elements by adjusting their height and firing an optional
   * callback after completion. Only the height is adjusted for this animation, causing all matched
   * elements to be hidden or shown in a "sliding" manner
   */
  public Effects slideToggle(int millisecs, Function... f) {
    return as(Effects).slideToggle(millisecs, f);
  }

  /**
   * Hide all matched elements by adjusting their height and firing an optional callback after
   * completion.
   */
  public Effects slideUp(Function... f) {
    return as(Effects).slideUp(f);
  }

  /**
   * Hide all matched elements by adjusting their height and firing an optional callback after
   * completion.
   */
  public Effects slideUp(int millisecs, Function... f) {
    return as(Effects).slideUp(millisecs, f);
  }

  /**
   * When .stop() is called on an element, the currently-running animation (if any) is immediately
   * stopped. If, for instance, an element is being hidden with .slideUp() when .stop() is called,
   * the element will now still be displayed, but will be a fraction of its previous height.
   * Callback functions are not called but the next animation in the queue begins immediately.
   */
  public GQuery stop() {
    return stop(false);
  }

  /**
   * When .stop() is called on an element, the currently-running animation (if any) is immediately
   * stopped. If, for instance, an element is being hidden with .slideUp() when .stop() is called,
   * the element will now still be displayed, but will be a fraction of its previous height.
   * Callback functions are not called but the next animation in the queue begins immediately.
   *
   * If the clearQueue parameter is provided with a value of true, then the rest of the animations
   * in the queue are removed and never run.
   */
  public GQuery stop(boolean clearQueue) {
    return stop(clearQueue, false);
  }

  /**
   * When .stop() is called on an element, the currently-running animation (if any) is immediately
   * stopped. If, for instance, an element is being hidden with .slideUp() when .stop() is called,
   * the element will now still be displayed, but will be a fraction of its previous height.
   * Callback functions are not called but the next animation in the queue begins immediately.
   *
   * If the clearQueue parameter is provided with a value of true, then the rest of the animations
   * in the queue are removed and never run.
   *
   * If the jumpToEnd property is provided with a value of true, the current animation stops, but
   * the element is immediately given its target values for each CSS property. The callback
   * functions are then immediately called, if provided.
   */
  public GQuery stop(boolean clearQueue, boolean jumpToEnd) {
    return as(Queue).stop(clearQueue, jumpToEnd);
  }

  /**
   * Bind a set of functions to the submit event of each matched element. Or submit a form if no
   * functions are provided.
   */
  public GQuery submit(Function... funcs) {
    return bindOrFire("submit", null, funcs);
  }

  /**
   * Return the concatened text contained in the matched elements.
   */
  public String text() {
    String result = "";
    for (Element e : elements) {
      result += JsUtils.text(e);
    }
    return result;
  }

  /**
   * Set the innerText of every matched element.
   */
  public GQuery text(String txt) {
    for (Element e : elements) {
      e.setInnerText(txt);
    }
    return this;
  }

  /**
   * Toggle visibility of elements.
   */
  public GQuery toggle() {
    for (Element e : elements) {
      if (getStyleImpl().isVisible(e)) {
        $(e).hide();
      } else {
        $(e).show();
        e.getStyle().setDisplay(Display.BLOCK);
      }
    }
    return this;
  }

  /**
   * Toggle among two or more function calls every other click.
   */
  public GQuery toggle(final Function... fn) {
    for (Element e : elements) {
      $(e).click(new Function() {
        int click = 0;

        public boolean f(Event e) {
          int n = fn.length == 1 ? 0 : (click++ % fn.length);
          return fn[n].f(e);
        }
      });
    }
    return this;
  }

  /**
   * Adds or removes the specified classes to each matched element depending on the class's
   * presence.
   */
  public GQuery toggleClass(String... classes) {
    for (Element e : elements) {
      for (String clz : classes) {
        if (hasClass(e, clz)) {
          e.removeClassName(clz);
        } else {
          e.addClassName(clz);
        }
      }
    }
    return this;
  }

  /**
   * Adds or removes the specified classes to each matched element depending on the value of the
   * switch argument.
   *
   * if addOrRemove is true, the class is added and in the case of false it is removed.
   */
  public GQuery toggleClass(String clz, boolean addOrRemove) {
    if (addOrRemove) {
      addClass(clz);
    } else {
      removeClass(clz);
    }
    return this;
  }

  /**
   * Returns the computed top position of the first element matched.
   */
  public int top() {
    return (int) cur("top", true);
  }

  /**
   * Produces a string representation of the matched elements.
   */
  public String toString() {
    return toString(false);
  }

  /**
   * Produces a string representation of the matched elements.
   */
  public String toString(boolean pretty) {
    String r = "";
    for (Element e : elements) {
      if (window.equals(e)) {
        continue;
      }
      String elStr;
      try {
        elStr = JsUtils.isXML(e) ? JsUtils.XML2String(e) : e.getString();
      } catch (Exception e2) {
        elStr =
            "< " + (e == null ? "null" : e.getNodeName())
                + "(gquery, error getting the element string representation: " + e2.getMessage()
                + ")/>";
      }
      r += (pretty && r.length() > 0 ? "\n " : "") + elStr;
    }
    return r;
  }

  /**
   * Trigger a browser native event on each matched element.
   */
  public GQuery trigger(NativeEvent event) {
    return as(Events).trigger(event, new Function[] {});
  }

  /**
   * Trigger a set of events on each matched element.
   *
   * For keyboard events you can pass a second parameter which represents the key-code of the pushed
   * key.
   *
   * Example: fire(Event.ONCLICK | Event.ONFOCUS) Example: fire(Event.ONKEYDOWN. 'a');
   */
  public GQuery trigger(int eventbits, int... keys) {
    return as(Events).trigger(eventbits, keys);
  }

  /**
   * Trigger a event in all matched elements.
   *
   * @param eventName An string representing the type of the event desired
   * @param datas Additional parameters to pass along to the event handlers.
   */
  public GQuery trigger(String eventName, Object... datas) {
    return as(Events).triggerHtmlEvent(eventName, datas);
  }

  /**
   * Removes all events that match the eventbits.
   */
  public GQuery unbind(int eventbits) {
    return as(Events).unbind(eventbits);
  }

  /**
   * Removes the function passed from the set of events which match the eventbits.
   */
  public GQuery unbind(int eventbits, Function f) {
    return as(Events).unbind(eventbits, null, f);
  }

  /**
   * Removes all events that match the eventList.
   */
  public GQuery unbind(String eventList) {
    return unbind(eventList, null);
  }

  /**
   * Removes all events that match the eventList.
   */
  public GQuery unbind(String eventList, Function f) {
    return as(Events).unbind(eventList, f);
  }

  /**
   * Remove all event delegation that have been bound using
   * {@link #delegate(String, int, Function...)} {@link #live(int, Function...)} methods.
   * 
   * @deprecated use {@link #off()}
   */
  public GQuery undelegate() {
    return as(Events).undelegate();
  }

  /**
   * Undelegate is a way of removing event handlers that have been bound using
   * {@link #delegate(String, int, Function...)} method.
   * 
   * @deprecated use {@link #off(String)}
   */
  public GQuery undelegate(String selector) {
    for (Element e : elements) {
      $(selector, e).die();
    }

    return this;
  }

  /**
   * Undelegate is a way of removing event handlers that have been bound using
   * {@link #delegate(String, int, Function...)} method.
   * 
   * @deprecated use {@link #off(String)}
   */
  public GQuery undelegate(String selector, int eventBit) {
    for (Element e : elements) {
      $(selector, e).die(eventBit);
    }

    return this;
  }

  /**
   * Undelegate is a way of removing event handlers that have been bound using
   * {@link #delegate(String, int, Function...)} method.
   * 
   * @deprecated use {@link #off(String, String)}
   */
  public GQuery undelegate(String selector, String eventName) {
    for (Element e : elements) {
      $(selector, e).die(eventName);
    }

    return this;
  }

  /**
   * Remove all duplicate elements from an array of elements. Note that this only works on arrays of
   * DOM elements, not strings or numbers.
   */
  public JsNodeArray unique(NodeList<Element> result) {
    return JsUtils.unique(result.<JsArray<Element>> cast()).cast();
  }

  /**
   * This method removes the element's parent. The matched elements replaces their parents within
   * the DOM structure. It is the inverse of {@link GQuery#wrap(GQuery)} method.
   *
   * @return
   */
  public GQuery unwrap() {

    for (Element parent : parent().elements) {
      if (!"body".equalsIgnoreCase(parent.getTagName())) {
        GQuery g = $(parent);
        g.replaceWith(g.children());
      }
    }
    return this;
  }

  /**
   * Gets the content of the value attribute of the first matched element, returns only the first
   * value even if it is a multivalued element. To get an array of all values in multivalues
   * elements use vals().
   *
   * When the first element is a radio-button and is not checked, then it looks for the first
   * checked radio-button that has the same name in the list of matched elements.
   *
   * When there are not matched elements it returns null.
   */
  public String val() {
    if (isEmpty()) {
      return null;
    }
    String[] v = vals();
    return v == null ? null : v.length > 0 ? v[0] : "";
  }

  /**
   * Sets the value attribute of every matched element based in the return value of the function
   * evaluated for this element.
   *
   * NOTE: in jquery the function receives the arguments in different way, first index and them the
   * actual value, but we use the normal way in gquery Function, first the element and second the
   * index.
   */
  public GQuery val(Function f) {
    for (int i = 0; i < size(); i++) {
      eq(i).val(f.f(get(i), i).toString());
    }
    return this;
  }

  /**
   * Sets the 'value' attribute of every matched element, but does not set the checked flag to
   * checkboxes or radiobuttons.
   *
   * If you wanted to set values in collections of checkboxes o radiobuttons use val(String[])
   * instead
   */
  public GQuery val(String value) {
    for (Element e : elements) {
      setElementValue(e, value);
    }
    return this;
  }

  /**
   * Sets the value of every matched element.
   *
   * There is a different behaviour depending on the element type:
   * <ul>
   * <li>select multiple: options whose value match any of the passed values will be set.
   * <li>select single: the last option whose value matches any of the passed values will be set.
   * <li>input radio: the last input whose value matches any of the passed values will be set.
   * <li>input checkbox: inputs whose value match any of the passed values will be set.
   * <li>textarea, button, and other input: value will set to a string result of joining with coma,
   * all passed values
   * </ul>
   *
   * NOTE: if you wanted call this function with just one parameter, you have to pass an array
   * signature to avoid call the overloaded val(String) method:
   *
   * $(...).val(new String[]{"value"});
   */
  public GQuery val(String... values) {
    String value = join(",", values);
    for (Element e : elements) {
      String name = e.getNodeName();
      if ("select".equalsIgnoreCase(name)) {
        SelectElement s = SelectElement.as(e);
        s.setSelectedIndex(-1);
        for (String v : values) {
          if (s.isMultiple()) {
            for (int i = 0, l = s.getOptions().getLength(); i < l; i++) {
              if (v.equals(s.getOptions().getItem(i).getValue())) {
                s.getOptions().getItem(i).setSelected(true);
              }
            }
          } else {
            s.setValue(v);
          }
        }
      } else if ("input".equalsIgnoreCase(name)) {
        InputElement ie = InputElement.as(e);
        String type = ie.getType();
        if ("radio".equalsIgnoreCase((type)) || "checkbox".equalsIgnoreCase(type)) {
          ie.setChecked(false);
          for (String v : values) {
            if (ie.getValue().equals(v)) {
              ie.setChecked(true);
              break;
            }
          }
        } else {
          ie.setValue(value);
        }
      } else {
        setElementValue(e, value);
      }
    }
    return this;
  }

  /**
   * Gets the content of the value attribute of the first matched element, returns more than one
   * value if it is a multiple select.
   *
   * When the first element is a radio-button and is not checked, then it looks for a the first
   * checked radio-button that has the same name in the list of matched elements.
   *
   * This method always returns an array. If no valid value can be determined the array will be
   * empty, otherwise it will contain one or more values.
   */
  public String[] vals() {
    if (!isEmpty()) {
      Element e = get(0);
      if (e.getNodeName().equalsIgnoreCase("select")) {
        SelectElement se = SelectElement.as(e);
        if (se.isMultiple()) {
          JsArrayString result = JsArrayString.createArray().cast();
          for (int i = 0, l = se.getOptions().getLength(); i < l; i++) {
            OptionElement oe = se.getOptions().getItem(i);
            if (oe.isSelected()) {
              result.set(result.length(), oe.getValue());
            }
          }
          return result.length() > 0 ? jsArrayToString(result) : null;
        } else if (se.getSelectedIndex() >= 0) {
          return new String[] {se.getOptions().getItem(se.getSelectedIndex()).getValue()};
        }
      } else if (e.getNodeName().equalsIgnoreCase("input")) {
        InputElement ie = InputElement.as(e);
        return new String[] {ie.getValue()};
      } else if (e.getNodeName().equalsIgnoreCase("textarea")) {
        return new String[] {TextAreaElement.as(e).getValue()};
      } else if (e.getNodeName().equalsIgnoreCase("button")) {
        return new String[] {ButtonElement.as(e).getValue()};
      }
    }
    return new String[0];
  }

  @Deprecated
  public boolean visible() {
    return isVisible();
  }

  /**
   * Return the first non null attached widget from the matched elements or null if there isn't any.
   */
  @SuppressWarnings("unchecked")
  public <W extends Widget> W widget() {
    return (W) widget(0);
  }

  /**
   * Return the nth non null attached widget from the matched elements or null if there isn't any.
   */
  public <W extends Widget> W widget(int n) {
    for (Element e : elements) {
      @SuppressWarnings("unchecked")
      W w = (W) getAssociatedWidget(e);
      if (w != null) {
        if (n == 0) {
          return w;
        }
        n--;
      }
    }
    return null;
  }

  /**
   * return the list of attached widgets matching the query.
   */
  public List<Widget> widgets() {
    List<Widget> widgets = new ArrayList<Widget>();
    for (Element e : elements) {
      Widget w = getAssociatedWidget(e);
      if (w != null) {
        widgets.add(w);
      }
    }
    return widgets;
  }

  /**
   * Return the list of attached widgets instance of the provided class matching the query.
   *
   * This method is very useful for decoupled views, so as we can access widgets from other views
   * without maintaining methods which export them.
   *
   */
  @SuppressWarnings("unchecked")
  public <W extends Widget> List<W> widgets(Class<W> clazz) {
    List<W> ret = new ArrayList<W>();
    for (Widget w : widgets()) {
      // isAssignableFrom does not work in gwt.
      Class<?> c = w.getClass();
      do {
        if (c.equals(clazz)) {
          ret.add((W) w);
          break;
        }
        c = c.getSuperclass();
      } while (c != null);
    }
    return ret;
  }

  /**
   * Get the current computed, pixel, width of the first matched element. It does not include
   * margin, padding nor border.
   */
  public int width() {
    return (int) cur("width", true);
  }

  /**
   * Set the width of every matched element.
   */
  public GQuery width(int width) {
    for (Element e : elements) {
      e.getStyle().setPropertyPx("width", width);
    }
    return this;
  }

  /**
   * Set the width style property of every matched element. It's useful for using 'percent' or 'em'
   * units Example: $(".a").width("100%")
   */
  public GQuery width(String width) {
    return css("width", width);
  }

  /**
   * Wrap each matched element with the specified HTML content. This wrapping process is most useful
   * for injecting additional structure into a document, without ruining the original semantic
   * qualities of a document. This works by going through the first element provided (which is
   * generated, on the fly, from the provided HTML) and finds the deepest descendant element within
   * its structure -- it is that element that will enwrap everything else.
   */
  public GQuery wrap(Element elem) {
    return wrap($(elem));
  }

  /**
   * Wrap each matched element with the specified HTML content. This wrapping process is most useful
   * for injecting additional structure into a document, without ruining the original semantic
   * qualities of a document. This works by going through the first element provided (which is
   * generated, on the fly, from the provided HTML) and finds the deepest descendant element within
   * its structure -- it is that element that will enwrap everything else.
   */
  public GQuery wrap(GQuery query) {
    for (Element e : elements) {
      $(e).wrapAll(query);
    }
    return this;
  }

  /**
   * Wrap each matched element with the specified HTML content. This wrapping process is most useful
   * for injecting additional structure into a document, without ruining the original semantic
   * qualities of a document. This works by going through the first element provided (which is
   * generated, on the fly, from the provided HTML) and finds the deepest descendant element within
   * its structure -- it is that element that will enwrap everything else.
   */
  public GQuery wrap(String html) {
    return wrap($(html));
  }

  /**
   * Wrap all the elements in the matched set into a single wrapper element. This is different from
   * .wrap() where each element in the matched set would get wrapped with an element. This wrapping
   * process is most useful for injecting additional structure into a document, without ruining the
   * original semantic qualities of a document.
   *
   * This works by going through the first element provided (which is generated, on the fly, from
   * the provided HTML) and finds the deepest descendant element within its structure -- it is that
   * element that will enwrap everything else.
   */
  public GQuery wrapAll(Element elem) {
    return wrapAll($(elem));
  }

  /**
   * Wrap all the elements in the matched set into a single wrapper element. This is different from
   * .wrap() where each element in the matched set would get wrapped with an element. This wrapping
   * process is most useful for injecting additional structure into a document, without ruining the
   * original semantic qualities of a document.
   *
   * This works by going through the first element provided (which is generated, on the fly, from
   * the provided HTML) and finds the deepest descendant element within its structure -- it is that
   * element that will enwrap everything else.
   */
  public GQuery wrapAll(GQuery query) {
    if (!isEmpty()) {
      GQuery wrap = query.clone();
      if (get(0).getParentNode() != null) {
        wrap.insertBefore(get(0));
      }
      for (Element e : wrap.elements) {
        Node n = e;
        while (n.getFirstChild() != null && n.getFirstChild().getNodeType() == Node.ELEMENT_NODE) {
          n = n.getFirstChild();
        }
        $((Element) n).append(this);
      }
    }
    return this;
  }

  /**
   * Wrap all the elements in the matched set into a single wrapper element. This is different from
   * .wrap() where each element in the matched set would get wrapped with an element. This wrapping
   * process is most useful for injecting additional structure into a document, without ruining the
   * original semantic qualities of a document.
   *
   * This works by going through the first element provided (which is generated, on the fly, from
   * the provided HTML) and finds the deepest descendant element within its structure -- it is that
   * element that will enwrap everything else.
   */
  public GQuery wrapAll(String html) {
    return wrapAll($(html));
  }

  /**
   * Wrap the inner child contents of each matched element (including text nodes) with an HTML
   * structure. This wrapping process is most useful for injecting additional structure into a
   * document, without ruining the original semantic qualities of a document. This works by going
   * through the first element provided (which is generated, on the fly, from the provided HTML) and
   * finds the deepest ancestor element within its structure -- it is that element that will enwrap
   * everything else.
   */
  public GQuery wrapInner(Element elem) {
    return wrapInner($(elem));
  }

  /**
   * Wrap the inner child contents of each matched element (including text nodes) with an HTML
   * structure. This wrapping process is most useful for injecting additional structure into a
   * document, without ruining the original semantic qualities of a document. This works by going
   * through the first element provided (which is generated, on the fly, from the provided HTML) and
   * finds the deepest ancestor element within its structure -- it is that element that will enwrap
   * everything else.
   */
  public GQuery wrapInner(GQuery query) {
    for (Element e : elements) {
      $(e).contents().wrapAll(query);
    }
    return this;
  }

  /**
   * Wrap the inner child contents of each matched element (including text nodes) with an HTML
   * structure. This wrapping process is most useful for injecting additional structure into a
   * document, without ruining the original semantic qualities of a document. This works by going
   * through the first element provided (which is generated, on the fly, from the provided HTML) and
   * finds the deepest ancestor element within its structure -- it is that element that will enwrap
   * everything else.
   */
  public GQuery wrapInner(String html) {
    return wrapInner($(html));
  }

  private String join(String chr, String... values) {
    String value = "";
    for (int i = 0; i < values.length; i++) {
      value += i > 0 ? chr + values[i] : values[i];
    }
    return value;
  }
}