From 2e40a536740b811d69a346d54a96bc80088e73b3 Mon Sep 17 00:00:00 2001
From: Ruben Vereecken <rubenvereecken@gmail.com>
Date: Sun, 15 Jun 2014 23:19:37 +0200
Subject: [PATCH] Extracting third party scripts out of main

---
 app/assets/main.html      | 108 -----------------------------------
 app/initialize.coffee     |  13 +++++
 app/lib/facebook.coffee   |  42 ++++++++++++++
 app/lib/filepicker.coffee |  28 +++++++++
 app/lib/google.coffee     |  16 ++++++
 app/lib/olark.coffee      | 116 ++++++++++++++++++++++++++++++++++++++
 app/lib/segmentio.coffee  |  41 ++++++++++++++
 app/lib/temp.txt          |  18 ++++++
 app/lib/twitter.coffee    |  12 ++++
 9 files changed, 286 insertions(+), 108 deletions(-)
 create mode 100644 app/lib/facebook.coffee
 create mode 100644 app/lib/filepicker.coffee
 create mode 100644 app/lib/google.coffee
 create mode 100644 app/lib/olark.coffee
 create mode 100644 app/lib/segmentio.coffee
 create mode 100644 app/lib/temp.txt
 create mode 100644 app/lib/twitter.coffee

diff --git a/app/assets/main.html b/app/assets/main.html
index b0fac676c..9f583173b 100644
--- a/app/assets/main.html
+++ b/app/assets/main.html
@@ -55,123 +55,15 @@
     authorize: true
   </script>
   <!-- end LinkedIn code -->
-  <!-- begin segment.io code -->
-  <script type="text/javascript">
-  var analytics=analytics||[];(function(){var e=["identify","track","trackLink","trackForm","trackClick","trackSubmit","page","pageview","ab","alias","ready","group"],t=function(e){return function(){analytics.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var n=0;n<e.length;n++)analytics[e[n]]=t(e[n])})(),analytics.load=function(e){var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src=("https:"===document.location.protocol?"https://":"http://")+"d2dq2ahtl5zl1z.cloudfront.net/analytics.js/v1/"+e+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(t,n)};
-  analytics.load("jsjzx9n4d2");
-  </script>
-  <!-- end segment.io code -->
-
-  <!-- begin olark code -->
-  <script data-cfasync="false" type='text/javascript'>/*<![CDATA[*/window.olark||(function(c){var f=window,d=document,l=f.location.protocol=="https:"?"https:":"http:",z=c.name,r="load";var nt=function(){
-    f[z]=function(){
-    (a.s=a.s||[]).push(arguments)};var a=f[z]._={
-    },q=c.methods.length;while(q--){(function(n){f[z][n]=function(){
-    f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={
-    0:+new Date};a.P=function(u){
-    a.p[u]=new Date-a.p[0]};function s(){
-    a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){
-    hd="head";return["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){
-    return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){
-    b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{
-    b.contentWindow[g].open()}catch(w){
-    c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{
-    var t=b.contentWindow[g];t.write(p());t.close()}catch(x){
-    b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({
-    loader: "static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});
-    /* custom configuration goes here (www.olark.com/documentation) */
-    olark.identify('1451-787-10-5544');/*]]>*/</script>
-  <!-- end olark code -->
-    
 
 </head>
 <body class="nano clearfix">
   <div id="fb-root"></div>
 
-<!-- begin facebook code -->
-  <script>
-    // Additional JS functions here
-    window.fbAsyncInit = function() {
-      Backbone.Mediator.publish('fbapi-loaded');
-      FB.init({
-        appId      : document.location.origin === 'http://localhost:3000' ? '607435142676437' : '148832601965463', // App ID
-        channelUrl : document.location.origin +'/channel.html', // Channel File
-        status     : true, // check login status
-        cookie     : true, // enable cookies to allow the server to access the session
-        xfbml      : true  // parse XFBML
-      });
-
-      // This is fired for any auth related change, such as login, logout or session refresh.
-      FB.Event.subscribe('auth.authResponseChange', function(response) {
-        // Here we specify what we do with the response anytime this event occurs. 
-        if (response.status === 'connected') {
-          // They have logged in to the app.
-          Backbone.Mediator.publish('facebook-logged-in', {response:response});
-        } else if (response.status === 'not_authorized') {
-          // The person is logged into Facebook, but not into the app.
-        } else {
-          // The person is not logged into Facebook
-        }
-      });
-    };
-
-    // Load the SDK asynchronously
-    (function(d){
-      var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
-      if (d.getElementById(id)) {return;}
-      js = d.createElement('script'); js.id = id; js.async = true;
-      js.src = "//connect.facebook.net/en_US/all.js";
-      //js.src = "//connect.facebook.net/en_US/all/debug.js";
-      ref.parentNode.insertBefore(js, ref);
-    }(document));
-  </script>
-  <!-- end facebook code -->
-
-
   <header class="header-container" id="header-container"></header>
   
   <div id="page-container" class="nano-content"></div>
 
   <div id="modal-wrapper" class="modal-content"></div>
-
-  <!-- begin google api/plus code -->
-  <script type="text/javascript">
-    (function() {
-      var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
-      po.src = 'https://apis.google.com/js/client:plusone.js?onload=onGPlusLoaded';
-      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
-    })();
-    
-    function onGPlusLoaded() {
-      Backbone.Mediator.publish('gapi-loaded');
-    }
-
-    function signinCallback(authResult) {
-      if (authResult['access_token']) {
-        Backbone.Mediator.publish('gplus-logged-in', authResult)
-      }
-    }
-  </script>
-  <!-- end google api/plus code -->
-
-  <!-- begin twitter code -->
-  <script>
-    (function (d,s,id) {
-      var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https';
-      if(!d.getElementById(id)) {
-        js = d.createElement(s);
-        js.id = id;
-        js.src = p + '://platform.twitter.com/widgets.js';
-        fjs.parentNode.insertBefore(js, fjs);
-      }
-    })(document, 'script', 'twitter-wjs');
-  </script>
-  <!-- end twitter code -->
-
-  <!-- begin filepicker.io code -->
-  <script type="text/javascript">
-    (function(a){if(window.filepicker){return}var b=a.createElement("script");b.type="text/javascript";b.async=!0;b.src=("https:"===a.location.protocol?"https:":"http:")+"//api.filepicker.io/v1/filepicker.js";var c=a.getElementsByTagName("script")[0];c.parentNode.insertBefore(b,c);var d={};d._queue=[];var e="pick,pickMultiple,pickAndStore,read,write,writeUrl,export,convert,store,storeUrl,remove,stat,setKey,constructWidget,makeDropPane".split(",");var f=function(a,b){return function(){b.push([a,arguments])}};for(var g=0;g<e.length;g++){d[e[g]]=f(e[g],d._queue)}window.filepicker=d})(document);
-  </script>
-  <!-- end filepicker.io code -->
 </body>
 </html>
diff --git a/app/initialize.coffee b/app/initialize.coffee
index 08e0a4b39..938a6188b 100644
--- a/app/initialize.coffee
+++ b/app/initialize.coffee
@@ -19,6 +19,7 @@ definitionSchemas =
 
 init = ->
   # Set up Backbone.Mediator schemas
+  initializeVendors()
   setUpDefinitions()
   setUpChannels()
   Backbone.Mediator.setValidationEnabled document.location.href.search(/codecombat.com/) is -1
@@ -60,3 +61,15 @@ setUpChannels = ->
 setUpDefinitions = ->
   for definition of definitionSchemas
     Backbone.Mediator.addDefSchemas definitionSchemas[definition]
+
+initializeVendors = ->
+  initializers =
+    filepicker: require './lib/filepicker'
+    #olark: require './lib/olark'
+    facebook: require './lib/facebook'
+    google: require './lib/google'
+    twitter: require './lib/twitter'
+    #segmentio: require './lib/segmentio'
+
+  for name, initializer of initializers
+    initializer() 
diff --git a/app/lib/facebook.coffee b/app/lib/facebook.coffee
new file mode 100644
index 000000000..bc4834c0b
--- /dev/null
+++ b/app/lib/facebook.coffee
@@ -0,0 +1,42 @@
+module.exports = initializeFacebook = ->
+  # Additional JS functions here
+  window.fbAsyncInit = ->
+    Backbone.Mediator.publish "fbapi-loaded"
+    FB.init
+      appId: (if document.location.origin is "http://localhost:3000" then "607435142676437" else "148832601965463") # App ID
+      channelUrl: document.location.origin + "/channel.html" # Channel File
+      status: true # check login status
+      cookie: true # enable cookies to allow the server to access the session
+      xfbml: true # parse XFBML
+
+    
+    # This is fired for any auth related change, such as login, logout or session refresh.
+    FB.Event.subscribe "auth.authResponseChange", (response) ->
+      
+      # Here we specify what we do with the response anytime this event occurs. 
+      if response.status is "connected"
+        
+        # They have logged in to the app.
+        Backbone.Mediator.publish "facebook-logged-in",
+          response: response
+
+      else if response.status is "not_authorized"
+        #
+      else
+	      # 
+
+  # Load the SDK asynchronously
+  ((d) ->
+    js = undefined
+    id = "facebook-jssdk"
+    ref = d.getElementsByTagName("script")[0]
+    return  if d.getElementById(id)
+    js = d.createElement("script")
+    js.id = id
+    js.async = true
+    js.src = "//connect.facebook.net/en_US/all.js"
+    
+    #js.src = "//connect.facebook.net/en_US/all/debug.js";
+    ref.parentNode.insertBefore js, ref
+    return
+  ) document
diff --git a/app/lib/filepicker.coffee b/app/lib/filepicker.coffee
new file mode 100644
index 000000000..5b4ee7f82
--- /dev/null
+++ b/app/lib/filepicker.coffee
@@ -0,0 +1,28 @@
+module.exports = initializeFilepicker = ->
+  ((a) ->
+    return  if window.filepicker
+    b = a.createElement("script")
+    b.type = "text/javascript"
+    b.async = not 0
+    b.src = ((if "https:" is a.location.protocol then "https:" else "http:")) + "//api.filepicker.io/v1/filepicker.js"
+    c = a.getElementsByTagName("script")[0]
+    c.parentNode.insertBefore b, c
+    d = {}
+    d._queue = []
+    e = "pick,pickMultiple,pickAndStore,read,write,writeUrl,export,convert,store,storeUrl,remove,stat,setKey,constructWidget,makeDropPane".split(",")
+    f = (a, b) ->
+      ->
+        b.push [
+          a
+          arguments_
+        ]
+        return
+
+    g = 0
+
+    while g < e.length
+      d[e[g]] = f(e[g], d._queue)
+      g++
+    window.filepicker = d
+    return
+  ) document
diff --git a/app/lib/google.coffee b/app/lib/google.coffee
new file mode 100644
index 000000000..c664efb86
--- /dev/null
+++ b/app/lib/google.coffee
@@ -0,0 +1,16 @@
+module.exports = initializeGoogle = ->
+  onGPlusLoaded = ->
+    Backbone.Mediator.publish "gapi-loaded"
+    return
+  signinCallback = (authResult) ->
+    Backbone.Mediator.publish "gplus-logged-in", authResult  if authResult["access_token"]
+    return
+  (->
+    po = document.createElement("script")
+    po.type = "text/javascript"
+    po.async = true
+    po.src = "https://apis.google.com/js/client:plusone.js?onload=onGPlusLoaded"
+    s = document.getElementsByTagName("script")[0]
+    s.parentNode.insertBefore po, s
+    return
+  )()
diff --git a/app/lib/olark.coffee b/app/lib/olark.coffee
new file mode 100644
index 000000000..09187223d
--- /dev/null
+++ b/app/lib/olark.coffee
@@ -0,0 +1,116 @@
+module.exports = initializeOlark = ->
+  window.olark or ((c) -> #<![CDATA[
+    f = window
+    d = document
+    l = (if f.location.protocol is "https:" then "https:" else "http:")
+    z = c.name
+    r = "load"
+    nt = ->
+      s = ->
+        a.P r
+        f[z] r
+        return
+      f[z] = ->
+        (a.s = a.s or []).push arguments_
+        return
+
+      a = f[z]._ = {}
+      q = c.methods.length
+      while q--
+        ((n) ->
+          f[z][n] = ->
+            f[z] "call", n, arguments_
+            return
+
+          return
+        ) c.methods[q]
+      a.l = c.loader
+      a.i = nt
+      a.p = 0: +new Date
+      a.P = (u) ->
+        a.p[u] = new Date - a.p[0]
+        return
+
+      (if f.addEventListener then f.addEventListener(r, s, false) else f.attachEvent("on" + r, s))
+      ld = ->
+        p = (hd) ->
+          hd = "head"
+          [
+            "<"
+            hd
+            "></"
+            hd
+            "><"
+            i
+            " onl" + "oad=\"var d="
+            g
+            ";d.getElementsByTagName('head')[0]."
+            j
+            "(d."
+            h
+            "('script'))."
+            k
+            "='"
+            l
+            "//"
+            a.l
+            "'"
+            "\""
+            "></"
+            i
+            ">"
+          ].join ""
+        i = "body"
+        m = d[i]
+        return setTimeout(ld, 100)  unless m
+        a.P 1
+        j = "appendChild"
+        h = "createElement"
+        k = "src"
+        n = d[h]("div")
+        v = n[j](d[h](z))
+        b = d[h]("iframe")
+        g = "document"
+        e = "domain"
+        o = undefined
+        n.style.display = "none"
+        m.insertBefore(n, m.firstChild).id = z
+        b.frameBorder = "0"
+        b.id = z + "-loader"
+        b.src = "javascript:false"  if /MSIE[ ]+6/.test(navigator.userAgent)
+        b.allowTransparency = "true"
+        v[j] b
+        try
+          b.contentWindow[g].open()
+        catch w
+          c[e] = d[e]
+          o = "javascript:var d=" + g + ".open();d.domain='" + d.domain + "';"
+          b[k] = o + "void(0);"
+        try
+          t = b.contentWindow[g]
+          t.write p()
+          t.close()
+        catch x
+          b[k] = o + "d.write(\"" + p().replace(/"/g, String.fromCharCode(92) + "\"") + "\");d.close();"
+        a.P 2
+        return
+
+      ld()
+      return
+
+    nt()
+    return
+  )(
+    loader: "static.olark.com/jsclient/loader0.js"
+    name: "olark"
+    methods: [
+      "configure"
+      "extend"
+      "declare"
+      "identify"
+    ]
+  )
+
+  # custom configuration goes here (www.olark.com/documentation) 
+  olark.identify "1451-787-10-5544" #]]>
+
diff --git a/app/lib/segmentio.coffee b/app/lib/segmentio.coffee
new file mode 100644
index 000000000..eae7dd588
--- /dev/null
+++ b/app/lib/segmentio.coffee
@@ -0,0 +1,41 @@
+module.exports = initializeSegmentio = ->
+  analytics = analytics or []
+  (->
+    e = [
+      "identify"
+      "track"
+      "trackLink"
+      "trackForm"
+      "trackClick"
+      "trackSubmit"
+      "page"
+      "pageview"
+      "ab"
+      "alias"
+      "ready"
+      "group"
+    ]
+    t = (e) ->
+      ->
+        analytics.push [e].concat(Array::slice.call(arguments_, 0))
+        return
+
+    n = 0
+
+    while n < e.length
+      analytics[e[n]] = t(e[n])
+      n++
+    return
+  )()
+  analytics.load = (e) ->
+    t = document.createElement("script")
+    t.type = "text/javascript"
+    t.async = not 0
+    t.src = ((if "https:" is document.location.protocol then "https://" else "http://")) + "d2dq2ahtl5zl1z.cloudfront.net/analytics.js/v1/" + e + "/analytics.min.js"
+
+    n = document.getElementsByTagName("script")[0]
+    n.parentNode.insertBefore t, n
+    return
+
+
+  analytics.load "jsjzx9n4d2"
diff --git a/app/lib/temp.txt b/app/lib/temp.txt
new file mode 100644
index 000000000..345d300f6
--- /dev/null
+++ b/app/lib/temp.txt
@@ -0,0 +1,18 @@
+/*<![CDATA[*/window.olark||(function(c){var f=window,d=document,l=f.location.protocol=="https:"?"https:":"http:",z=c.name,r="load";var nt=function(){
+    f[z]=function(){
+    (a.s=a.s||[]).push(arguments)};var a=f[z]._={
+    },q=c.methods.length;while(q--){(function(n){f[z][n]=function(){
+    f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={
+    0:+new Date};a.P=function(u){
+    a.p[u]=new Date-a.p[0]};function s(){
+    a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){
+    hd="head";return["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){
+    return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){
+    b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{
+    b.contentWindow[g].open()}catch(w){
+    c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{
+    var t=b.contentWindow[g];t.write(p());t.close()}catch(x){
+    b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({
+    loader: "static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});
+    /* custom configuration goes here (www.olark.com/documentation) */
+    olark.identify('1451-787-10-5544');/*]]>*/
diff --git a/app/lib/twitter.coffee b/app/lib/twitter.coffee
new file mode 100644
index 000000000..eaba1f36f
--- /dev/null
+++ b/app/lib/twitter.coffee
@@ -0,0 +1,12 @@
+module.exports = initializeTwitter = ->
+  ((d, s, id) ->
+    js = undefined
+    fjs = d.getElementsByTagName(s)[0]
+    p = (if /^http:/.test(d.location) then "http" else "https")
+    unless d.getElementById(id)
+      js = d.createElement(s)
+      js.id = id
+      js.src = p + "://platform.twitter.com/widgets.js"
+      fjs.parentNode.insertBefore js, fjs
+    return
+  ) document, "script", "twitter-wjs"