// Generate sample JS code that is equivalent but that loads at
// very different rates on different browsers
// Posted on blog.lexspoon.org on June 29, 2010


///////////// OPTIONS ///////////////////////////

// Whether to indirect all global variables through a jslink object
val jslink = false

// Whether to emit a wrapper function
val wrapper = false

// Whether to chunk the body of the wrapper function into smaller functions
val chunk = false



///////////// IMPLEMENTATION ///////////////////////////

import java.io.FileWriter
import java.io.PrintWriter


// write out test.html
{
  val out = new PrintWriter(new FileWriter("test.html"))
  out.println("""
<html>
<head>
<script>
  function millis() { return (new Date()).getTime(); }
  window.startTime = millis();
</script>
</head>
<body>
<iframe src="module.html"></iframe>
</body>
</html>
""")
  out.close()
}


// write out module.html
{
  val out = new PrintWriter(new FileWriter("module.html"))
  out.println("""
<html>
<head>
<script>
""")

  if (wrapper)
    out.println("(function () {")

  if (jslink)
    out.println("var jslink = {};")

  def emitFoo(i: Int) {
    if (jslink)
      out.print("jslink.foo" + i + " = function() { ")
    else
      out.print("function foo" + i + "() { ")
    out.print("var a = 0; var b = 1; var c = ")
    if (jslink)
      out.print("jslink.")
    out.println("foo" + (i+1) + " }")
  }

  if (chunk) {
    for (chunk <- 0 until 34) {
      out.println("(function () {")
      for (i <- chunk*1000 until (chunk+1)*1000)
        emitFoo(i)
      out.println("})();")
    }
  } else {
    for (i <- 0 until 34000)
      emitFoo(i)
  }
  
  if (wrapper)
    out.println("})()")

  out.println("""
$wnd = parent
$wnd.endTime = $wnd.millis()
alert("initial load time = " + ($wnd.endTime - $wnd.startTime))
</script>
</head>
<body>
</body>
</html>
""")

  out.close()
}

