// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Distinguish between having the plugin loaded vs. being run using chromeapp.html.
var isChromeApp = /chromeapp.html$/.exec(location.href);

exports.runAtStartUp = function(func) {
  if (isChromeApp) {
    var mobile = require('org.chromium.bootstrap.mobile.impl');
    mobile.onBackgroundPageLoaded.subscribe(func);
  } else {
    document.addEventListener('deviceready', func, false);
  }
};

exports.queueLifeCycleEvent = function(func) {
  if (isChromeApp) {
    var mobile = require('org.chromium.bootstrap.mobile.impl');
    mobile.lifeCycleEventFuncs.push(func);
  } else {
    document.addEventListener('deviceready', func, false);
  }
};

@@ -304,16 +304,122 @@
 .href);%0A
+var channel = require('cordova/channel');%0A%0A// TODO: Delete this method if favour of delayDeviceReadyUntil.
 %0Aexports
@@ -464,32 +464,93 @@
 (isChromeApp) %7B%0A
+    // TODO: Implement done() call back for chrome app case.%0A
     var mobile =
@@ -667,70 +667,801 @@
     
-document.addEventListener('
+channel.onCordovaReady.subscribe(func);%0A  %7D%0A%7D;%0A%0A// TODO: Add this to cordova-js.%0A// Executes func after onCordovaReady fires, and delays deviceready until done() is called.%0Aexports.delayDeviceReadyUntil = function(func) %7B%0A  channel.onCordovaReady.subscribe(function() %7B%0A    var newChannel = channel.createSticky('cca-delay-
 device
+-
 ready'
-, func, false
+);%0A    channel.deviceReadyChannelsArray.push(newChannel);%0A    func(function done() %7B%0A      newChannel.fire(
 );%0A
+  
   %7D
-%0A%7D;%0A
+);%0A  %7D);%0A%7D;%0A%0A// For Chrome Apps:%0A//  - Call func after background page is loaded.%0A//  - Prevents onLaunched from being fired%0A//  - func() called immeditately if start-up sequence has already completed.%0A// For vanilla Cordova:%0A//  - Call func after deviceready has been fired.%0A//  - func() called immeditately if deviceready has already fired.
 %0Aexp
@@ -1581,32 +1581,72 @@
 .mobile.impl');%0A
+    if (mobile.lifeCycleEventFuncs) %7B%0A  
     mobile.lifeC
@@ -1664,32 +1664,34 @@
 ncs.push(func);%0A
+  
   %7D else %7B%0A    d
@@ -1693,62 +1693,356 @@
     
-document.addEventListener('d
+  // Initial events have already occurred.%0A      func();%0A    %7D%0A  %7D else %7B%0A    if (channel.onDeviceReady.state == 1) %7B%0A      // Fire after deviceready, and within a setTimeout to allow%0A      // user code to register listeners.%0A      channel.onD
 evice
-r
+R
 eady
-', func, false);
+.subscribe(function() %7B%0A        setTimeout(func, 0);%0A      %7D);%0A    %7D else %7B%0A      func();%0A    %7D
 %0A  %7D

Change helpers.delayDeviceReadyUntil() and helpers.queueLifeCycleEvent()