var htmlrunner,
    resultdir,
    appKey,
    appId,
    appUrl,
    page,
    fs;

phantom.injectJs("../../lib/core.js")

if ( phantom.args.length !== 5 ) {
    console.log("Usage: phantom_test_runner.js HTML_RUNNER APP_ID APP_KEY APP_URL RESULT_DIR");
    phantom.exit();
} else {
    htmlrunner = phantom.args[0];
    appId = phantom.args[1];
    appKey = phantom.args[2];
    appUrl = phantom.args[3];
    resultdir = phantom.args[4];
    page = require("webpage").create();
    fs = require("fs");
    
    // Echo the output of the tests to the Standard Output
    page.onConsoleMessage = function(msg, source, linenumber) {
        console.log(msg);
    };

    page.open(htmlrunner + "?app_key=" + appKey + "&app_id=" + appId + "&app_url=" + appUrl, function(status) {
        if (status === "success") {
            utils.core.waitfor(function() { // wait for this to be true
                return page.evaluate(function() {
                    return typeof(jasmine.phantomjsXMLReporterPassed) !== "undefined";
                });
            }, function() { // once done...
                // Retrieve the result of the tests
                var f = null, i, len;
                    suitesResults = page.evaluate(function(){
                    return jasmine.phantomjsXMLReporterResults;
                });
                
                // Save the result of the tests in files
                for ( i = 0, len = suitesResults.length; i < len; ++i ) {
                    try {
                        f = fs.open(resultdir + '/' + suitesResults[i]["xmlfilename"], "w");
                        f.write(suitesResults[i]["xmlbody"]);
                        f.close();
                    } catch (e) {
                        console.log(e);
                        console.log("phantomjs> Unable to save result of Suite '"+ suitesResults[i]["xmlfilename"] +"'");
                    }
                }
                
                // Return the correct exit status. '0' only if all the tests passed
                phantom.exit(page.evaluate(function(){
                    return jasmine.phantomjsXMLReporterPassed ? 0 : 1; //< exit(0) is success, exit(1) is failure
                }));
            }, function() { // or, once it timesout...
	            console.log("TIMEOUT");
                phantom.exit(1);
            }, 20000); //20 second timeout just in case
        } else {
            console.log("phantomjs> Could not load '" + htmlrunner + "'.");
            phantom.exit(1);
        }
    });
}

@@ -2347,17 +2347,18 @@
      %7D, 
-2
+18
 0000); /
@@ -2362,17 +2362,16 @@
 ; //
-20 second
+3 minute
  tim
@@ -2387,16 +2387,17 @@
  in case
+!
 %0A       

increase timeout for phantomjs testing