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

    /**
     * Casper prototype
     */
    phantom.Casper.prototype = {
        /**
         * Encodes a resource using the base64 algorithm synchroneously using
         * client-side XMLHttpRequest.
         *
         * NOTE: we cannot use window.btoa() for some strange reasons here.
         *
         * @param  String  url  The url to download
         * @return string       Base64 encoded result
         */
        base64encode: function(url) {
            return this.evaluate(function() {
                return __utils__.getBase64(__casper_params__.url);
            }, {
                url: url
            });
        },

        /**
         * Proxy method for WebPage#render. Adds a clipRect parameter for
         * automatically set page clipRect setting values and sets it back once
         * done. If the cliprect parameter is omitted, the full page viewport
         * area will be rendered.
         *
         * @param  String  targetFile  A target filename
         * @param  mixed   clipRect    An optional clipRect object (optional)
         * @return Casper
         */
        capture: function(targetFile, clipRect) {
            var previousClipRect;
            if (clipRect) {
                if (typeof clipRect !== "object") {
                    throw new Error("clipRect must be an Object instance.");
                }
                previousClipRect = this.page.clipRect;
                this.page.clipRect = clipRect;
                this.log('Capturing page to ' + targetFile + ' with clipRect' + JSON.stringify(clipRect), "debug");
            } else {
                this.log('Capturing page to ' + targetFile, "debug");
            }
            try {
                this.page.render(targetFile);
            } catch (e) {
                this.log('Failed to capture screenshot as ' + targetFile + ': ' + e, "error");
            }
            if (previousClipRect) {
                this.page.clipRect = previousClipRect;
            }
            return this;
        },

        /**
         * Captures the page area containing the provided selector.
         *
         * @param  String  targetFile  Target destination file path.
         * @param  String  selector    CSS3 selector
         * @return Casper
         */
        captureSelector: function(targetFile, selector) {
            return this.capture(targetFile, this.evaluate(function() {
                try {
                    var clipRect = document.querySelector(__casper_params__.selector).getBoundingClientRect();
                    return {
                        top:    clipRect.top,
                        left:   clipRect.left,
                        width:  clipRect.width,
                        height: clipRect.height
                    };
                } catch (e) {
                    __utils__.log("Unable to fetch bounds for element " + __casper_params__.selector, "warning");
                }
            }, {
                selector: selector
            }));
        },

        /**
         * Checks for any further navigation step to process.
         *
         * @param  Casper    self        A self reference
         * @param  function  onComplete  An options callback to apply on completion
         */
        checkStep: function(self, onComplete) {
            var step = self.steps[self.step];
            if (!self.loadInProgress && typeof step === "function") {
                var curStepNum = self.step + 1;
                var stepInfo   = "Step " + curStepNum + "/" + self.steps.length + ": ";
                self.log(stepInfo + self.page.evaluate(function() {
                    return document.location.href;
                }) + ' (HTTP ' + self.currentHTTPStatus + ')', "info");
                try {
                    step(self);
                } catch (e) {
                    if (self.options.faultTolerant) {
                        self.log("Step error: " + e, "error");
                    } else {
                        throw e;
                    }
                }
                var time = new Date().getTime() - self.startTime;
                self.log(stepInfo + "done in " + time + "ms.", "info");
                self.step++;
            }
            if (typeof step !== "function" && !self.delayedExecution) {
                self.result.time = new Date().getTime() - self.startTime;
                self.log("Done " + self.steps.length + " steps in " + self.result.time + 'ms.', "info");
                clearInterval(self.checker);
                if (typeof onComplete === "function") {
                    try {
                        onComplete(self);
                    } catch (err) {
                        self.log("could not complete final step: " + err, "error");
                    }
                } else {
                    // default behavior is to exit phantom
                    self.exit();
                }
            }
        },

        /**
         * Emulates a click on the element from the provided selector, if
         * possible. In case of success, `true` is returned.
         *
         * @param  String   selector        A DOM CSS3 compatible selector
         * @param  Boolean  fallbackToHref  Whether to try to relocate to the value of any href attribute (default: true)
         * @return Boolean
         */
        click: function(selector, fallbackToHref) {
            fallbackToHref = typeof(fallbackToHref) == "undefined" ? true : !!fallbackToHref;
            this.log("click on selector: " + selector, "debug");
            return this.evaluate(function() {
                return __utils__.click(__casper_params__.selector, __casper_params__.fallbackToHref);
            }, {
                selector:       selector,
                fallbackToHref: fallbackToHref
            });
        },

        /**
         * Logs the HTML code of the current page.
         *
         * @return Casper
         */
        debugHTML: function() {
            this.echo(this.evaluate(function() {
                return document.body.innerHTML;
            }));
            return this;
        },

        /**
         * Logs the textual contents of the current page.
         *
         * @return Casper
         */
        debugPage: function() {
            this.echo(this.evaluate(function() {
                return document.body.innerText;
            }));
            return this;
        },

        /**
         * Exit phantom on failure, with a logged error message.
         *
         * @param  String  message  An optional error message
         * @param  Number  status   An optional exit status code (must be > 0)
         * @return Casper
         */
        die: function(message, status) {
            this.result.status = 'error';
            this.result.time = new Date().getTime() - this.startTime;
            message = typeof message === "string" && message.length > 0 ? message : DEFAULT_DIE_MESSAGE;
            this.log(message, "error");
            if (typeof this.options.onDie === "function") {
                this.options.onDie(this, message, status);
            }
            return this.exit(Number(status) > 0 ? Number(status) : 1);
        },

        /**
         * Iterates over the values of a provided array and execute a callback
         * for each item.
         *
         * @param  Array     array
         * @param  Function  fn     Callback: function(self, item, index)
         * @return Casper
         */
        each: function(array, fn) {
            if (array.constructor !== Array) {
                self.log("each() only works with arrays", "error");
                return this;
            }
            (function(self) {
                array.forEach(function(item, i) {
                    fn(self, item, i);
                });
            })(this);
            return this;
        },

        /**
         * Prints something to stdout.
         *
         * @param  String  text  A string to echo to stdout
         * @return Casper
         */
        echo: function(text, style) {
            console.log(style ? this.colorizer.colorize(text, style) : text);
            return this;
        },

        /**
         * Evaluates an expression in the page context, a bit like what
         * WebPage#evaluate does, but can also replace values by their
         * placeholer names:
         *
         *     casper.evaluate(function() {
         *         document.querySelector('#username').value = '%username%';
         *         document.querySelector('#password').value = '%password%';
         *         document.querySelector('#submit').click();
         *     }, {
         *         username: 'Bazoonga',
         *         password: 'baz00nga'
         *     })
         *
         * As an alternative, CasperJS injects a `__casper_params__` Object
         * instance containing all the parameters you passed:
         *
         *     casper.evaluate(function() {
         *         document.querySelector('#username').value = __casper_params__.username;
         *         document.querySelector('#password').value = __casper_params__.password;
         *         document.querySelector('#submit').click();
         *     }, {
         *         username: 'Bazoonga',
         *         password: 'baz00nga'
         *     })
         *
         * FIXME: waiting for a patch of PhantomJS to allow direct passing of
         * arguments to the function.
         * TODO: don't forget to keep this backward compatible.
         *
         * @param  function  fn            The function to be evaluated within current page DOM
         * @param  object    replacements  Parameters to pass to the remote environment
         * @return mixed
         * @see    WebPage#evaluate
         */
        evaluate: function(fn, replacements) {
            replacements = typeof(replacements) === "object" ? replacements : {};
            this.page.evaluate(replaceFunctionPlaceholders(function() {
                window.__casper_params__ = {};
                try {
                    var jsonString = unescape(decodeURIComponent('%replacements%'));
                    window.__casper_params__ = JSON.parse(jsonString);
                } catch (e) {
                    __utils__.log("Unable to replace parameters: " + e, "error");
                }
            }, {
                replacements: encodeURIComponent(escape(JSON.stringify(replacements).replace("'", "\'")))
            }));
            return this.page.evaluate(replaceFunctionPlaceholders(fn, replacements));
        },

        /**
         * Evaluates an expression within the current page DOM and die() if it
         * returns false.
         *
         * @param  function  fn       The expression to evaluate
         * @param  String    message  The error message to log
         * @return Casper
         */
        evaluateOrDie: function(fn, message) {
            if (!this.evaluate(fn)) {
                return this.die(message);
            }
            return this;
        },

        /**
         * Checks if an element matching the provided CSS3 selector exists in
         * current page DOM.
         *
         * @param  String  selector  A CSS3 selector
         * @return Boolean
         */
        exists: function(selector) {
            return this.evaluate(function() {
                return __utils__.exists(__casper_params__.selector);
            }, {
                selector: selector
            });
        },

        /**
         * Exits phantom.
         *
         * @param  Number  status  Status
         * @return Casper
         */
        exit: function(status) {
            phantom.exit(status);
            return this;
        },

        /**
         * Fetches innerText within the element(s) matching a given CSS3
         * selector.
         *
         * @param  String  selector  A CSS3 selector
         * @return String
         */
        fetchText: function(selector) {
            return this.evaluate(function() {
                return __utils__.fetchText(__casper_params__.selector);
            }, {
                selector: selector
            });
        },

        /**
         * Fills a form with provided field values.
         *
         * @param  String  selector  A CSS3 selector to the target form to fill
         * @param  Object  vals      Field values
         * @param  Boolean submit    Submit the form?
         */
        fill: function(selector, vals, submit) {
            submit = submit === true ? submit : false;
            if (typeof selector !== "string" || !selector.length) {
                throw "form selector must be a non-empty string";
            }
            if (typeof vals !== "object") {
                throw "form values must be provided as an object";
            }
            var fillResults = this.evaluate(function() {
               return __utils__.fill(__casper_params__.selector, __casper_params__.values);
            }, {
                selector: selector,
                values:   vals
            });
            if (!fillResults) {
                throw "unable to fill form";
            } else if (fillResults.errors.length > 0) {
                (function(self){
                    fillResults.errors.forEach(function(error) {
                        self.log("form error: " + error, "error");
                    });
                })(this);
                if (submit) {
                    this.log("errors encountered while filling form; submission aborted", "warning");
                    submit = false;
                }
            }
            // File uploads
            if (fillResults.files && fillResults.files.length > 0) {
                (function(self) {
                    fillResults.files.forEach(function(file) {
                        var fileFieldSelector = [selector, 'input[name="' + file.name + '"]'].join(' ');
                        self.page.uploadFile(fileFieldSelector, file.path);
                    });
                })(this);
            }
            // Form submission?
            if (submit) {
                this.evaluate(function() {
                    var form = document.querySelector(__casper_params__.selector);
                    var method = form.getAttribute('method').toUpperCase() || "GET";
                    var action = form.getAttribute('action') || "unknown";
                    __utils__.log('submitting form to ' + action + ', HTTP ' + method, 'info');
                    form.submit();
                }, {
                    selector: selector
                });
            }
        },

        /**
         * Retrieve current document url.
         *
         * @return String
         */
        getCurrentUrl: function() {
            return decodeURIComponent(this.evaluate(function() {
                return document.location.href;
            }));
        },

        /**
         * Retrieves current page title, if any.
         *
         * @return String
         */
        getTitle: function() {
            return this.evaluate(function() {
                return document.title;
            });
        },

        /**
         * Logs a message.
         *
         * @param  String  message  The message to log
         * @param  String  level    The log message level (from Casper.logLevels property)
         * @param  String  space    Space from where the logged event occured (default: "phantom")
         * @return Casper
         */
        log: function(message, level, space) {
            level = level && this.logLevels.indexOf(level) > -1 ? level : "debug";
            space = space ? space : "phantom";
            if (level === "error" && typeof this.options.onError === "function") {
                this.options.onError(this, message, space);
            }
            if (this.logLevels.indexOf(level) < this.logLevels.indexOf(this.options.logLevel)) {
                return this; // skip logging
            }
            if (this.options.verbose) {
                var levelStr = this.colorizer.colorize('[' + level + ']', this.logStyles[level]);
                this.echo(levelStr + ' [' + space + '] ' + message); // direct output
            }
            this.result.log.push({
                level:   level,
                space:   space,
                message: message,
                date:    new Date().toString()
            });
            return this;
        },

        /**
         * Opens a page. Takes only one argument, the url to open (using the
         * callback argument would defeat the whole purpose of Casper
         * actually).
         *
         * @param  String  location  The url to open
         * @return Casper
         */
        open: function(location) {
            this.requestUrl = location;
            this.page.open(location);
            return this;
        },

        /**
         * Repeats a step a given number of times.
         *
         * @param  Number    times  Number of times to repeat step
         * @aram   function  then   The step closure
         * @return Casper
         * @see    Casper#then
         */
        repeat: function(times, then) {
            for (var i = 0; i < times; i++) {
                this.then(then);
            }
            return this;
        },

        /**
         * Runs the whole suite of steps.
         *
         * @param  function  onComplete  an optional callback
         * @param  Number    time        an optional amount of milliseconds for interval checking
         * @return Casper
         */
        run: function(onComplete, time) {
            if (!this.steps || this.steps.length < 1) {
                this.log("No steps defined, aborting", "error");
                return this;
            }
            this.log("Running suite: " + this.steps.length + " step" + (this.steps.length > 1 ? "s" : ""), "info");
            this.checker = setInterval(this.checkStep, (time ? time: 250), this, onComplete);
            return this;
        },

        /**
         * Configures and starts Casper.
         *
         * @param  String   location  An optional location to open on start
         * @param  function then      Next step function to execute on page loaded (optional)
         * @return Casper
         */
        start: function(location, then) {
            if (this.started) {
                this.log("start failed: Casper has already started!", "error");
            }
            this.log('Starting...', "info");
            this.startTime = new Date().getTime();
            this.steps = [];
            this.step = 0;
            // Option checks
            if (this.logLevels.indexOf(this.options.logLevel) < 0) {
                this.log("Unknown log level '" + this.options.logLevel + "', defaulting to 'warning'", "warning");
                this.options.logLevel = "warning";
            }
            // WebPage
            if (!isWebPage(this.page)) {
                if (isWebPage(this.options.page)) {
                    this.page = this.options.page;
                } else {
                    this.page = createPage(this);
                }
            }
            this.page.settings = mergeObjects(this.page.settings, this.options.pageSettings);
            if (typeof this.options.clipRect === "object") {
                this.page.clipRect = this.options.clipRect;
            }
            if (typeof this.options.viewportSize === "object") {
                this.page.viewportSize = this.options.viewportSize;
            }
            this.started = true;
            if (typeof this.options.timeout === "number" && this.options.timeout > 0) {
                self.log("execution timeout set to " + this.options.timeout + 'ms', "info");
                setTimeout(function(self) {
                    self.log("timeout of " + self.options.timeout + "ms exceeded", "info").exit();
                }, this.options.timeout, this);
            }
            if (typeof this.options.onPageInitialized === "function") {
                this.log("Post-configuring WebPage instance", "debug");
                this.options.onPageInitialized(this.page);
            }
            if (typeof location === "string" && location.length > 0) {
                if (typeof then === "function") {
                    return this.open(location).then(then);
                } else {
                    return this.open(location);
                }
            }
            return this;
        },

        /**
         * Schedules the next step in the navigation process.
         *
         * @param  function  step  A function to be called as a step
         * @return Casper
         */
        then: function(step) {
            if (!this.started) {
                throw "Casper not started; please use Casper#start";
            }
            if (typeof step !== "function") {
                throw "You can only define a step as a function";
            }
            this.steps.push(step);
            return this;
        },

        /**
         * Adds a new navigation step for clicking on a provided link selector
         * and execute an optional next step.
         *
         * @param  String   selector        A DOM CSS3 compatible selector
         * @param  Function then            Next step function to execute on page loaded (optional)
         * @param  Boolean  fallbackToHref  Whether to try to relocate to the value of any href attribute (default: true)
         * @return Casper
         * @see    Casper#click
         * @see    Casper#then
         */
        thenClick: function(selector, then, fallbackToHref) {
            this.then(function(self) {
                self.click(selector, fallbackToHref);
            });
            return typeof then === "function" ? this.then(then) : this;
        },

        /**
         * Adds a new navigation step to perform code evaluation within the
         * current retrieved page DOM.
         *
         * @param  function  fn            The function to be evaluated within current page DOM
         * @param  object    replacements  Optional replacements to performs, eg. for '%foo%' => {foo: 'bar'}
         * @return Casper
         * @see    Casper#evaluate
         */
        thenEvaluate: function(fn, replacements) {
            return this.then(function(self) {
                self.evaluate(fn, replacements);
            });
        },

        /**
         * Adds a new navigation step for opening the provided location.
         *
         * @param  String   location  The URL to load
         * @param  function then      Next step function to execute on page loaded (optional)
         * @return Casper
         * @see    Casper#open
         */
        thenOpen: function(location, then) {
            this.then(function(self) {
                self.open(location);
            });
            return typeof then === "function" ? this.then(then) : this;
        },

        /**
         * Adds a new navigation step for opening and evaluate an expression
         * against the DOM retrieved from the provided location.
         *
         * @param  String    location      The url to open
         * @param  function  fn            The function to be evaluated within current page DOM
         * @param  object    replacements  Optional replacements to performs, eg. for '%foo%' => {foo: 'bar'}
         * @return Casper
         * @see    Casper#evaluate
         * @see    Casper#open
         */
        thenOpenAndEvaluate: function(location, fn, replacements) {
            return this.thenOpen(location).thenEvaluate(fn, replacements);
        },

        /**
         * Changes the current viewport size.
         *
         * @param  Number  width   The viewport width, in pixels
         * @param  Number  height  The viewport height, in pixels
         * @return Casper
         */
        viewport: function(width, height) {
            if (typeof width !== "number" || typeof height !== "number" || width <= 0 || height <= 0) {
                throw new Error("Invalid viewport width/height set: " + width + 'x' + height);
            }
            this.page.viewportSize = {
                width: width,
                height: height
            };
            return this;
        },

        /**
         * Adds a new step that will wait for a given amount of time (expressed
         * in milliseconds) before processing an optional next one.
         *
         * @param  Number    timeout  The max amount of time to wait, in milliseconds
         * @param  Function  then     Next step to process (optional)
         * @return Casper
         */
        wait: function(timeout, then) {
            if (typeof(timeout) !== "number" || Number(timeout, 10) < 1) {
                this.die("wait() only accepts a positive integer > 0 as a timeout value");
            }
            if (then && typeof(then) !== "function") {
                this.die("wait() a step definition must be a function");
            }
            return this.then(function(self) {
                self.delayedExecution = true;
                var start = new Date().getTime();
                var interval = setInterval(function(self, then) {
                    if (new Date().getTime() - start > timeout) {
                        self.delayedExecution = false;
                        self.log("wait() finished wating for " + timeout + "ms.", "info");
                        if (then) {
                            self.then(then);
                        }
                        clearInterval(interval);
                    }
                }, 100, self, then);
            });
        },

        /**
         * Waits until a function returns true to process a next step.
         *
         * @param  Function  testFx     A function to be evaluated for returning condition satisfecit
         * @param  Function  then       The next step to perform (optional)
         * @param  Function  onTimeout  A callback function to call on timeout (optional)
         * @param  Number    timeout    The max amount of time to wait, in milliseconds (optional)
         * @return Casper
         */
        waitFor: function(testFx, then, onTimeout, timeout) {
            timeout = timeout ? timeout : this.defaultWaitTimeout;
            if (typeof testFx !== "function") {
                this.die("waitFor() needs a test function");
            }
            if (then && typeof then !== "function") {
                this.die("waitFor() next step definition must be a function");
            }
            this.delayedExecution = true;
            var start = new Date().getTime();
            var condition = false;
            var interval = setInterval(function(self, testFx, onTimeout) {
                if ((new Date().getTime() - start < timeout) && !condition) {
                    condition = testFx(self);
                } else {
                    self.delayedExecution = false;
                    if (!condition) {
                        self.log("Casper.waitFor() timeout", "warning");
                        if (typeof onTimeout === "function") {
                            onTimeout(self);
                        } else {
                            self.die("Expired timeout, exiting.", "error");
                        }
                        clearInterval(interval);
                    } else {
                        self.log("waitFor() finished in " + (new Date().getTime() - start) + "ms.", "info");
                        if (then) {
                            self.then(then);
                        }
                        clearInterval(interval);
                    }
                }
            }, 100, this, testFx, onTimeout);
            return this;
        },

        /**
         * Waits until an element matching the provided CSS3 selector exists in
         * remote DOM to process a next step.
         *
         * @param  String    selector   A CSS3 selector
         * @param  Function  then       The next step to perform (optional)
         * @param  Function  onTimeout  A callback function to call on timeout (optional)
         * @param  Number    timeout    The max amount of time to wait, in milliseconds (optional)
         * @return Casper
         */
        waitForSelector: function(selector, then, onTimeout, timeout) {
            timeout = timeout ? timeout : this.defaultWaitTimeout;
            return this.waitFor(function(self) {
                return self.exists(selector);
            }, then, onTimeout, timeout);
        }
    };

    /**
     * Extends Casper's prototype with provided one.
     *
     * @param  Object  proto  Prototype methods to add to Casper
     */
    phantom.Casper.extend = function(proto) {
        if (typeof proto !== "object") {
            throw "extends() only accept objects";
        }
        mergeObjects(phantom.Casper.prototype, proto);
    };

    /**
     * Casper client-side helpers.
     */
    phantom.Casper.ClientUtils = function() {
        /**
         * Clicks on the DOM element behind the provided selector.
         *
         * @param  String  selector        A CSS3 selector to the element to click
         * @param  Boolean fallbackToHref  Whether to try to relocate to the value of any href attribute (default: true)
         * @return Boolean
         */
        this.click = function(selector, fallbackToHref) {
            fallbackToHref = typeof(fallbackToHref) == "undefined" ? true : !!fallbackToHref;
            var elem = this.findOne(selector);
            if (!elem) {
                return false;
            }
            var evt = document.createEvent("MouseEvents");
            evt.initMouseEvent("click", true, true, window, 1, 1, 1, 1, 1, false, false, false, false, 0, elem);
            if (elem.dispatchEvent(evt)) {
                return true;
            }
            if (fallbackToHref && elem.hasAttribute('href')) {
                document.location = elem.getAttribute('href');
                return true;
            }
            return false;
        };

        /**
         * Base64 encodes a string, even binary ones. Succeeds where
         * window.btoa() fails.
         *
         * @param  String  str
         * @return string
         */
        this.encode = function(str) {
            var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
            var out = "", i = 0, len = str.length, c1, c2, c3;
            while (i < len) {
                c1 = str.charCodeAt(i++) & 0xff;
                if (i == len) {
                    out += CHARS.charAt(c1 >> 2);
                    out += CHARS.charAt((c1 & 0x3) << 4);
                    out += "==";
                    break;
                }
                c2 = str.charCodeAt(i++);
                if (i == len) {
                    out += CHARS.charAt(c1 >> 2);
                    out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
                    out += CHARS.charAt((c2 & 0xF) << 2);
                    out += "=";
                    break;
                }
                c3 = str.charCodeAt(i++);
                out += CHARS.charAt(c1 >> 2);
                out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
                out += CHARS.charAt(c3 & 0x3F);
            }
            return out;
        };

        /**
         * Checks if a given DOM element exists in remote page.
         *
         * @param  String  selector  CSS3 selector
         * @return Boolean
         */
        this.exists = function(selector) {
            try {
                return document.querySelectorAll(selector).length > 0;
            } catch (e) {
                return false;
            }
        };

        /**
         * Fetches innerText within the element(s) matching a given CSS3
         * selector.
         *
         * @param  String  selector  A CSS3 selector
         * @return String
         */
        this.fetchText = function(selector) {
            var text = '', elements = this.findAll(selector);
            if (elements && elements.length) {
                Array.prototype.forEach.call(elements, function(element) {
                    text += element.innerText;
                });
            }
            return text;
        };

        /**
         * Fills a form with provided field values, and optionnaly submits it.
         *
         * @param  HTMLElement|String  form    A form element, or a CSS3 selector to a form element
         * @param  Object              vals    Field values
         * @return Object                      An object containing setting result for each field, including file uploads
         */
        this.fill = function(form, vals) {
            var out = {
                errors: [],
                fields: [],
                files:  []
            };
            if (!(form instanceof HTMLElement) || typeof form === "string") {
                __utils__.log("attempting to fetch form element from selector: '" + form + "'", "info");
                try {
                    form = document.querySelector(form);
                } catch (e) {
                    if (e.name === "SYNTAX_ERR") {
                        out.errors.push("invalid form selector provided: '" + form + "'");
                        return out;
                    }
                }
            }
            if (!form) {
                out.errors.push("form not found");
                return out;
            }
            for (var name in vals) {
                if (!vals.hasOwnProperty(name)) {
                    continue;
                }
                var field = form.querySelectorAll('[name="' + name + '"]');
                var value = vals[name];
                if (!field) {
                    out.errors.push('no field named "' + name + '" in form');
                    continue;
                }
                try {
                    out.fields[name] = this.setField(field, value);
                } catch (err) {
                    if (err.name === "FileUploadError") {
                        out.files.push({
                            name: name,
                            path: err.path
                        });
                    } else {
                        throw err;
                    }
                }
            }
            return out;
        };

        /**
         * Finds all DOM elements matching by the provided selector.
         *
         * @param  String  selector  CSS3 selector
         * @return NodeList|undefined
         */
        this.findAll = function(selector) {
            try {
                return document.querySelectorAll(selector);
            } catch (e) {
                this.log('findAll(): invalid selector provided "' + selector + '":' + e, "error");
            }
        };

        /**
         * Finds a DOM element by the provided selector.
         *
         * @param  String  selector  CSS3 selector
         * @return HTMLElement|undefined
         */
        this.findOne = function(selector) {
            try {
                return document.querySelector(selector);
            } catch (e) {
                this.log('findOne(): invalid selector provided "' + selector + '":' + e, "errors");
            }
        };

        /**
         * Downloads a resource behind an url and returns its base64-encoded
         * contents.
         *
         * @param  String  url  The resource url
         * @return String       Base64 contents string
         */
        this.getBase64 = function(url) {
            return this.encode(this.getBinary(url));
        };

        /**
         * Retrieves string contents from a binary file behind an url. Silently
         * fails but log errors.
         *
         * @param  String  url
         * @return string
         */
        this.getBinary = function(url) {
            try {
                var xhr = new XMLHttpRequest();
                xhr.open("GET", url, false);
                xhr.overrideMimeType("text/plain; charset=x-user-defined");
                xhr.send(null);
                return xhr.responseText;
            } catch (e) {
                if (e.name === "NETWORK_ERR" && e.code === 101) {
                    this.log("unfortunately, casperjs cannot make cross domain ajax requests", "warning");
                }
                this.log("error while fetching " + url + ": " + e, "error");
                return "";
            }
        };

        /**
         * Logs a message.
         *
         * @param  String  message
         * @param  String  level
         */
        this.log = function(message, level) {
            console.log("[casper:" + (level || "debug") + "] " + message);
        };

        /**
         * Sets a field (or a set of fields) value. Fails silently, but log
         * error messages.
         *
         * @param  HTMLElement|NodeList  field  One or more element defining a field
         * @param  mixed                 value  The field value to set
         */
        this.setField = function(field, value) {
            var fields, out;
            value = value || "";
            if (field instanceof NodeList) {
                fields = field;
                field = fields[0];
            }
            if (!field instanceof HTMLElement) {
                this.log("invalid field type; only HTMLElement and NodeList are supported", "error");
            }
            this.log('set "' + field.getAttribute('name') + '" field value to ' + value, "debug");
            try {
                field.focus();
            } catch (e) {
                __utils__.log("Unable to focus() input field " + field.getAttribute('name') + ": " + e, "warning");
            }
            var nodeName = field.nodeName.toLowerCase();
            switch (nodeName) {
                case "input":
                    var type = field.getAttribute('type') || "text";
                    switch (type.toLowerCase()) {
                        case "color":
                        case "date":
                        case "datetime":
                        case "datetime-local":
                        case "email":
                        case "hidden":
                        case "month":
                        case "number":
                        case "password":
                        case "range":
                        case "search":
                        case "tel":
                        case "text":
                        case "time":
                        case "url":
                        case "week":
                            field.value = value;
                            break;
                        case "checkbox":
                            field.setAttribute('checked', value ? "checked" : "");
                            break;
                        case "file":
                            throw {
                                name:    "FileUploadError",
                                message: "file field must be filled using page.uploadFile",
                                path:    value
                            };
                        case "radio":
                            if (fields) {
                                Array.prototype.forEach.call(fields, function(e) {
                                    e.checked = (e.value === value);
                                });
                            } else {
                                out = 'provided radio elements are empty';
                            }
                            break;
                        default:
                            out = "unsupported input field type: " + type;
                            break;
                    }
                    break;
                case "select":
                case "textarea":
                    field.value = value;
                    break;
                default:
                    out = 'unsupported field type: ' + nodeName;
                    break;
            }
            try {
                field.blur();
            } catch (err) {
                __utils__.log("Unable to blur() input field " + field.getAttribute('name') + ": " + err, "warning");
            }
            return out;
        };
    };

    /**
     * This is a port of lime colorizer.
     * http://trac.symfony-project.org/browser/tools/lime/trunk/lib/lime.php)
     *
     * (c) Fabien Potencier, Symfony project, MIT license
     */
    phantom.Casper.Colorizer = function() {
        var options    = { bold: 1, underscore: 4, blink: 5, reverse: 7, conceal: 8 };
        var foreground = { black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, white: 37 };
        var background = { black: 40, red: 41, green: 42, yellow: 43, blue: 44, magenta: 45, cyan: 46, white: 47 };
        var styles     = {
            'ERROR':     { bg: 'red', fg: 'white', bold: true },
            'INFO':      { fg: 'green', bold: true },
            'TRACE':     { fg: 'green', bold: true },
            'PARAMETER': { fg: 'cyan' },
            'COMMENT':   { fg: 'yellow' },
            'WARNING':   { fg: 'red', bold: true },
            'GREEN_BAR': { fg: 'white', bg: 'green', bold: true },
            'RED_BAR':   { fg: 'white', bg: 'red', bold: true },
            'INFO_BAR':  { fg: 'cyan', bold: true }
        };

        /**
         * Adds a style to provided text.
         *
         * @params  String  text
         * @params  String  styleName
         * @return  String
         */
        this.colorize = function(text, styleName) {
            if (styleName in styles) {
                return this.format(text, styles[styleName]);
            }
            return text;
        };

        /**
         * Formats a text using a style declaration object.
         *
         * @param  String  text
         * @param  Object  style
         * @return String
         */
        this.format = function(text, style) {
            if (typeof style !== "object") {
                return text;
            }
            var codes = [];
            if (style.fg && foreground[style.fg]) {
                codes.push(foreground[style.fg]);
            }
            if (style.bg && background[style.bg]) {
                codes.push(background[style.bg]);
            }
            for (var option in options) {
                if (style[option] === true) {
                    codes.push(options[option]);
                }
            }
            return "\033[" + codes.join(';') + 'm' + text + "\033[0m";
        };
    };

    /**
     * Casper tester: makes assertions, stores test results and display then.
     *
     */
    phantom.Casper.Tester = function(casper, options) {
        this.options = typeof options === "object" || {};
        if (!casper instanceof phantom.Casper) {
            throw "phantom.Casper.Tester needs a phantom.Casper instance";
        }

        // locals
        var exporter = new phantom.Casper.XUnitExporter();
        var PASS = this.options.PASS || "PASS";
        var FAIL = this.options.FAIL || "FAIL";

        // properties
        this.testResults = {
            passed: 0,
            failed: 0
        };

        // methods
        /**
         * Asserts a condition resolves to true.
         *
         * @param  Boolean  condition
         * @param  String   message    Test description
         */
        this.assert = function(condition, message) {
            var status = PASS;
            if (condition === true) {
                style = 'INFO';
                this.testResults.passed++;
                exporter.addSuccess("unknown", message);
            } else {
                status = FAIL;
                style = 'RED_BAR';
                this.testResults.failed++;
                exporter.addFailure("unknown", message, 'test failed', "assert");
            }
            casper.echo([this.colorize(status, style), this.formatMessage(message)].join(' '));
        };

        /**
         * Asserts that two values are strictly equals.
         *
         * @param  Boolean  testValue  The value to test
         * @param  Boolean  expected   The expected value
         * @param  String   message    Test description
         */
        this.assertEquals = function(testValue, expected, message) {
            if (expected === testValue) {
                casper.echo(this.colorize(PASS, 'INFO') + ' ' + this.formatMessage(message));
                this.testResults.passed++;
                exporter.addSuccess("unknown", message);
            } else {
                casper.echo(this.colorize(FAIL, 'RED_BAR') + ' ' + this.formatMessage(message, 'WARNING'));
                this.comment('     got:      ' + testValue);
                this.comment('     expected: ' + expected);
                this.testResults.failed++;
                exporter.addFailure("unknown", message, "test failed; expected: " + expected + "; got: " + testValue, "assertEquals");
            }
        };

        /**
         * Asserts that a code evaluation in remote DOM resolves to true.
         *
         * @param  Function  fn         A function to be evaluated in remote DOM
         * @param  String    message    Test description
         */
        this.assertEval = function(fn, message) {
            return this.assert(casper.evaluate(fn), message);
        };

        /**
         * Asserts that the result of a code evaluation in remote DOM equals
         * an expected value.
         *
         * @param  Function fn         The function to be evaluated in remote DOM
         * @param  Boolean  expected   The expected value
         * @param  String   message    Test description
         */
        this.assertEvalEquals = function(fn, expected, message) {
            return this.assertEquals(casper.evaluate(fn), expected, message);
        };

        /**
         * Asserts that an element matching the provided CSS3 selector exists in
         * remote DOM.
         *
         * @param  String   selector   CSS3 selectore
         * @param  String   message    Test description
         */
        this.assertExists = function(selector, message) {
            return this.assert(casper.exists(selector), message);
        };

        /**
         * Asserts that a provided string matches a provided RegExp pattern.
         *
         * @param  String   subject    The string to test
         * @param  RegExp   pattern    A RegExp object instance
         * @param  String   message    Test description
         */
        this.assertMatch = function(subject, pattern, message) {
            return this.assert(pattern.test(subject), message);
        };

        /**
         * Asserts that the provided function called with the given parameters
         * will raise an exception.
         *
         * @param  Function  fn       The function to test
         * @param  Array     args     The arguments to pass to the function
         * @param  String    message  Test description
         */
        this.assertRaises = function(fn, args, message) {
            try {
                fn.apply(null, args);
                this.fail(message);
            } catch (e) {
                this.pass(message);
            }
        };

        /**
         * Asserts that at least an element matching the provided CSS3 selector
         * exists in remote DOM.
         *
         * @param  String   selector   A CSS3 selector string
         * @param  String   message    Test description
         */
        this.assertSelectorExists = function(selector, message) {
            return this.assert(this.exists(selector), message);
        };

        /**
         * Asserts that title of the remote page equals to the expected one.
         *
         * @param  String  expected   The expected title string
         * @param  String  message    Test description
         */
        this.assertTitle = function(expected, message) {
            return this.assertEquals(casper.getTitle(), expected, message);
        };

        /**
         * Asserts that the provided input is of the given type.
         *
         * @param  mixed   input    The value to test
         * @param  String  type     The javascript type name
         * @param  String  message  Test description
         */
        this.assertType = function(input, type, message) {
            return this.assertEquals(betterTypeOf(input), type, message);
        };

        /**
         * Asserts that a the current page url matches the provided RegExp
         * pattern.
         *
         * @param  RegExp   pattern    A RegExp object instance
         * @param  String   message    Test description
         */
        this.assertUrlMatch = function(pattern, message) {
            return this.assertMatch(casper.getCurrentUrl(), pattern, message);
        };

        /**
         * Render a colorized output. Basically a proxy method for
         * Casper.Colorizer#colorize()
         */
        this.colorize = function(message, style) {
            return casper.colorizer.colorize(message, style);
        };

        /**
         * Writes a comment-style formatted message to stdout.
         *
         * @param  String  message
         */
        this.comment = function(message) {
            casper.echo('# ' + message, 'COMMENT');
        };

        /**
         * Writes an error-style formatted message to stdout.
         *
         * @param  String  message
         */
        this.error = function(message) {
            casper.echo(message, 'ERROR');
        };

        /**
         * Adds a failed test entry to the stack.
         *
         * @param  String  message
         */
        this.fail = function(message) {
            this.assert(false, message);
        };

        /**
         * Formats a message to highlight some parts of it.
         *
         * @param  String  message
         * @param  String  style
         */
        this.formatMessage = function(message, style) {
            var parts = /([a-z0-9_\.]+\(\))(.*)/i.exec(message);
            if (!parts) {
                return message;
            }
            return this.colorize(parts[1], 'PARAMETER') + this.colorize(parts[2], style);
        };

        /**
         * Writes an info-style formatted message to stdout.
         *
         * @param  String  message
         */
        this.info = function(message) {
            casper.echo(message, 'PARAMETER');
        };

        /**
         * Adds a successful test entry to the stack.
         *
         * @param  String  message
         */
        this.pass = function(message) {
            this.assert(true, message);
        };

        /**
         * Render tests results, an optionnaly exit phantomjs.
         *
         * @param  Boolean  exit
         */
        this.renderResults = function(exit, status, save) {
            save = typeof save === "string" ? save : this.options.save;
            var total = this.testResults.passed + this.testResults.failed, statusText, style, result;
            if (this.testResults.failed > 0) {
                statusText = FAIL;
                style = 'RED_BAR';
            } else {
                statusText = PASS;
                style = 'GREEN_BAR';
            }
            result = statusText + ' ' + total + ' tests executed, ' + this.testResults.passed + ' passed, ' + this.testResults.failed + ' failed.';
            if (result.length < 80) {
                result += new Array(80 - result.length + 1).join(' ');
            }
            casper.echo(this.colorize(result, style));
            if (save && typeof require === "function") {
                try {
                    require('fs').write(save, exporter.getXML(), 'w');
                    casper.echo('result log stored in ' + save, 'INFO');
                } catch (e) {
                    casper.echo('unable to write results to ' + save + '; ' + e, 'ERROR');
                }
            }
            if (exit === true) {
                casper.exit(status || 0);
            }
        };
    };

    /**
     * JUnit XML (xUnit) exporter for test results.
     *
     */
    phantom.Casper.XUnitExporter = function() {
        var node = function(name, attributes) {
            var node = document.createElement(name);
            for (var attrName in attributes) {
                var value = attributes[attrName];
                if (attributes.hasOwnProperty(attrName) && typeof attrName === "string") {
                    node.setAttribute(attrName, value);
                }
            }
            return node;
        };

        var xml = node('testsuite');
        xml.toString = function() {
            return this.outerHTML; // ouch
        };

        /**
         * Adds a successful test result
         *
         * @param  String  classname
         * @param  String  name
         */
        this.addSuccess = function(classname, name) {
            xml.appendChild(node('testcase', {
                classname: classname,
                name:      name
            }));
        };

        /**
         * Adds a failed test result
         *
         * @param  String  classname
         * @param  String  name
         * @param  String  message
         * @param  String  type
         */
        this.addFailure = function(classname, name, message, type) {
            var fnode = node('testcase', {
                classname: classname,
                name:      name
            });
            var failure = node('failure', {
                type: type || "unknown"
            });
            failure.appendChild(document.createTextNode(message || "no message left"));
            fnode.appendChild(failure);
            xml.appendChild(fnode);
        };

        /**
         * Retrieves generated XML object - actually an HTMLElement.
         *
         * @return HTMLElement
         */
        this.getXML = function() {
            return xml;
        };
    };

    /**
     * Provides a better typeof operator equivalent, able to retrieve the array
     * type.
     *
     * @param  mixed  input
     * @return String
     * @see    http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
     */
    function betterTypeOf(input) {
        try {
            return Object.prototype.toString.call(input).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
        } catch (e) {
            return typeof input;
        }
    }

    /**
     * Creates a new WebPage instance for Casper use.
     *
     * @param  Casper  casper  A Casper instance
     * @return WebPage
     */
    function createPage(casper) {
        var page;
        if (phantom.version.major <= 1 && phantom.version.minor < 3 && typeof require === "function") {
            page = new WebPage();
        } else {
            page = require('webpage').create();
        }
        page.onConsoleMessage = function(msg) {
            var level = "info", test = /^\[casper:(\w+)\]\s?(.*)/.exec(msg);
            if (test && test.length === 3) {
                level = test[1];
                msg = test[2];
            }
            casper.log(msg, level, "remote");
        };
        page.onLoadStarted = function() {
            casper.loadInProgress = true;
        };
        page.onLoadFinished = function(status) {
            if (status !== "success") {
                var message = 'Loading resource failed with status=' + status;
                if (casper.currentHTTPStatus) {
                    message += ' (HTTP ' + casper.currentHTTPStatus + ')';
                }
                message += ': ' + casper.requestUrl;
                casper.log(message, "warning");
                if (typeof casper.options.onLoadError === "function") {
                    casper.options.onLoadError(casper, casper.requestUrl, status);
                }
            }
            if (casper.options.clientScripts) {
                for (var i = 0; i < casper.options.clientScripts.length; i++) {
                    var script = casper.options.clientScripts[i];
                    if (casper.page.injectJs(script)) {
                        casper.log('Automatically injected ' + script + ' client side', "debug");
                    } else {
                        casper.log('Failed injecting ' + script + ' client side', "debug");
                    }
                }
            }
            // Client utils injection
            var injected = page.evaluate(replaceFunctionPlaceholders(function() {
                eval("var ClientUtils = " + decodeURIComponent("%utils%"));
                __utils__ = new ClientUtils();
                return __utils__ instanceof ClientUtils;
            }, {
                utils: encodeURIComponent(phantom.Casper.ClientUtils.toString())
            }));
            if (!injected) {
                casper.log("Failed to inject Casper client-side utilities!", "warning");
            } else {
                casper.log("Successfully injected Casper client-side utilities", "debug");
            }
            casper.loadInProgress = false;
        };
        page.onResourceReceived = function(resource) {
            if (resource.url === casper.requestUrl) {
                casper.currentHTTPStatus = resource.status;
                casper.currentUrl = resource.url;
            }
        };
        return page;
    }

    /**
     * Checks if the provided var is a WebPage instance
     *
     * @param  mixed  what
     * @return Boolean
     */
    function isWebPage(what) {
        if (!what || typeof what !== "object") {
            return false;
        }
        if (phantom.version.major <= 1 && phantom.version.minor < 3 && typeof require === "function") {
            return what instanceof WebPage;
        } else {
            return what.toString().indexOf('WebPage(') === 0;
        }
    }

    /**
     * Object recursive merging utility.
     *
     * @param  Object  obj1  the destination object
     * @param  Object  obj2  the source object
     * @return Object
     */
    function mergeObjects(obj1, obj2) {
        for (var p in obj2) {
            try {
                if (obj2[p].constructor == Object) {
                    obj1[p] = mergeObjects(obj1[p], obj2[p]);
                } else {
                    obj1[p] = obj2[p];
                }
            } catch(e) {
              obj1[p] = obj2[p];
            }
        }
        return obj1;
    }

    /**
     * Replaces a function string contents with placeholders provided by an
     * Object.
     *
     * @param  Function  fn            The function
     * @param  Object    replacements  Object containing placeholder replacements
     * @return String                  A function string representation
     */
    function replaceFunctionPlaceholders(fn, replacements) {
        if (replacements && typeof replacements === "object") {
            fn = fn.toString();
            for (var placeholder in replacements) {
                var match = '%' + placeholder + '%';
                do {
                    fn = fn.replace(match, replacements[placeholder]);
                } while(fn.indexOf(match) !== -1);
            }
        }
        return fn;
    }
})(phantom);