addOnDocumentReady(document, code, WINDOW_LOAD_BLOCK_ID, eventDeclaration);
}
private static void addOnDocumentReady(Document document, String code, String blockId, String eventDeclaration) {
// Create or locate script
Element script = DomUtils.getElementById(document, "script", blockId);
if (script == null) {
script = new Element("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("id", blockId);
String text = "\n//<![CDATA[\n" + eventDeclaration + "(function(){\n});\n//]]>\n";
script.addChild(new Text(text, false));
DomUtils.getElementsByTagName(document, "body").get(0).addChild(script);
}
// Build indented code
StringBuilder codeSb = new StringBuilder();
StringTokenizer lines = new StringTokenizer(code, "\n");
while (lines.hasMoreTokens()) {
codeSb.append("\t").append(lines.nextToken()).append("\n");
}
codeSb.append("");
// Add new code to existent script text
StringBuilder scriptSb = new StringBuilder(((Text) script.getFirstChild()).getContent());
scriptSb.delete(scriptSb.length() - "});\n//]]>\n".length(), scriptSb.length());
scriptSb.append(codeSb.toString());
scriptSb.append("});\n//]]>\n");
((Text) script.getFirstChild()).setContent(scriptSb.toString());
}