
// Change this to set the name of the managed resource store to create.
// You use the name with the createManagedStore, and removeManagedStore,
// and openManagedStore APIs. It isn't visible to the user.
var STORE_NAME = "opn_offline";

// Change this to set the URL of tha manifest file, which describe which
// URLs to capture. It can be relative to the current page, or an
// absolute URL.
var MANIFEST_FILENAME = "gears_manifest_auto.json";

var localServer;
var store;

var opn_gears_disabled = false;

// Called onload to initialize local server and store variables
function initgears() {
  if (!window.google || !google.gears) {
    textOut("Get Gears");
  } else {
	
	try{
    	localServer = google.gears.factory.create("beta.localserver");
    	store = localServer.createManagedStore(STORE_NAME);
		opn_gears_disabled = false;
    	textOut("Gears Enabled");
	}catch (e){
		opn_gears_disabled = true;
		textOut("Gears Disabled");
	}
  }
}

function gearsInfo(){
	alert("Install Google Gears to speed up the opennetwork experience.\n\nVisit gears.google.com to download and learn more.");
}

function gearsEnable(){
	ok = true;
	try{
    	localServer = google.gears.factory.create("beta.localserver");
    	store = localServer.createManagedStore(STORE_NAME);
		opn_gears_disabled = false;
    	textOut("Gears Enabled");
	}catch (e){
		opn_gears_disabled = true;
		textOut("Gears Disabled");
		ok = false;
	}
	
	if( ok ){
		gearsSync();
	}
}

// Create the managed resource store
function createStore() {
  if (!window.google || !google.gears) {
    alert("You must install Gears first.");
    return;
  }

	
	if( opn_gears_disabled ){
		//gearsEnable();
		alert("Please reload the page,\nand accept the 'Trust us with Gears' dialog.");
		return;
	}
	
	gearsSync();
}

function gearsSync(){

  textOut("Syncronizing...");
	
  store.manifestUrl = MANIFEST_FILENAME;
  store.checkForUpdate();

  var timerId = window.setInterval(function() {
    // When the currentVersion property has a value, all of the resources
    // listed in the manifest file for that version are captured. There is
    // an open bug to surface this state change as an event.
    if (store.currentVersion) {
      window.clearInterval(timerId);
      textOut("v."+ store.currentVersion +" OK");
	  window.setTimeout(function(){ textOut("Gears Updated"); }, 1000);
    } else if (store.updateStatus == 3) {
      textOut("Error: " + store.lastErrorMessage);
    }
  }, 500);  
}

// Remove the managed resource store.
function removeStore() {
  if (!window.google || !google.gears) {
    alert("You must install Gears first.");
    return;
  }

  localServer.removeManagedStore(STORE_NAME);
  textOut("Removed.");
}

// Utility function to output some status text.
function textOut(s) {
	
 var elm = document.getElementById("gears_label");
  while (elm.firstChild) {
    elm.removeChild(elm.firstChild);
  } 
  elm.appendChild(document.createTextNode(s));
}
