// 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 MANIFEST_STORE_NAME = "my_manifest_offline_docset";
var manifest_localServer;
var manifest_store;

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

// Change this to set the name of the dynamic resource store to create.
var ADD_STORE_NAME = "my_dynamic_offline_docset";
var add_localServer;
var add_store;

// Images to show status of current document's offline/online status
var OFF_IMAGE = "http://www.irt.org/offline/star_off.gif";
var ON_IMAGE = "http://www.irt.org/offline/star_on.gif";

// Image element id
var cacheStatus = "cacheStatus";

var OFF_TITLE = "Click to add current page to offline access";
var ON_TITLE = "Click to remove current page from offline cache";

// boolean to indicate if store creationg was successful
var GEARS_ENABLED = false;

// Boolean to control if textOut outputs status messages
// can be overruled by page loading this JavaScript
var google_gears_debug = false;

// Called onload to initialize local server and store variables
function init() {
  if (!window.google || !google.gears) {
    textOut("NOTE:  You must install Google Gears first.");
  } else {
    try {
      manifest_localServer = google.gears.factory.create("beta.localserver","1.0");
      add_localServer = google.gears.factory.create("beta.localserver","1.0");
      GEARS_ENABLED = true;
    }
    catch (ex) {
      textOut("Oh dear, Google Gears access was denied.");
      return;
    }
    manifest_store = manifest_localServer.createManagedStore(MANIFEST_STORE_NAME);
    add_store = add_localServer.createStore(ADD_STORE_NAME);
    textOut("Yeay, Google Gears is already installed.");

    checkImages();
//    var elm = document.getElementById(cacheStatus);
//    checkImageToggleforUrl(elm, window.location.href);
  }
}

function checkImages() {
  for (var i=0;i<document.images.length;i++) {
    var img = document.images[i];
    if (img.id.indexOf(cacheStatus) == 0) {
      checkImageToggleforUrl(img, window.location.href);
    }
  }
}

// Utility functions to check if Google Gears is installed and enabled
// Shows alert message if warn is set to true
// Returns true if Google Gears is installed and enabled
// Else returns false

function isGoogleGearsEnabled(warn) {
  if (!isGoogleGearsInstalled(warn)) {
    return false;
  }
  return isGoogleGearsEnabled(warn);
}

function isGoogleGearsInstalled(warn) {
  if (!window.google || !google.gears) {
    if (warn) alert("You must install Google Gears first.");
    return false;
  }
  return true;
}

function isGoogleGearsEnabled(warn) {
  if (!GEARS_ENABLED) {
    if (warn) alert("You must enable Google Gears first.");
    return false;
  }
  return true;
}

// Create the managed resource store
function createManagedStore() {
  if (isGoogleGearsEnabled(true)) {
    manifest_store.manifestUrl = MANIFEST_FILENAME;
    manifest_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 (manifest_store.currentVersion) {
        window.clearInterval(timerId);
        textOut("The documents are now available offline.\n" + 
                "With your browser offline, load the document at " +
                "its normal online URL to see the locally stored " +
			          "version. The version stored is: " + 
                manifest_store.currentVersion);
      } else if (manifest_store.updateStatus == 3) {
        textOut("Error: " + manifest_store.lastErrorMessage);
      }
    }, 500);  
  }
}

// Remove the managed resource store.
function removeManagedStore() {
  if (isGoogleGearsEnabled(true)) {
    manifest_localServer.removeManagedStore(MANIFEST_STORE_NAME);
    textOut("Done. The local store has been removed." +
          "You will now see online versions of the documents.");
  }
}

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



// Callback function called when url has been captured
function addUrlCallback(url, success, captureId) {
  textOut((success ? "Added:" : "Failed:") + " (" + captureId + ") " + url);
  //var elm = document.getElementById(cacheStatus);
  //checkImageToggleforUrl(elm, window.location.href);
  checkImages();
}

// Add the url to the dynamic resource store
function addUrlToStore(url) {
  if (isGoogleGearsEnabled(true)) {
    add_store.capture(url, addUrlCallback);
  }
}

// Remove the url from the dynamic resource store
function removeUrlFromStore(url) {
  if (isGoogleGearsEnabled(true)) {
    add_store.remove(url);
    textOut("Removed: " + url);
  }
}

// Remove the dynamic resource store - not called by anything at the moment
function removeAddStore() {
  if (isGoogleGearsEnabled(true)) {
    add_localServer.removeManagedStore(ADD_STORE_NAME);
    textOut("Done. The local store has been removed." +
          "You will now see online versions of the documents.");
  }
}

// Check if url is in dynamic resource store and set image src appropriately
function checkImageToggleforUrl(img, url) {
  if (isGoogleGearsEnabled(true)) {
    var src = add_store.isCaptured(url) ? ON_IMAGE : OFF_IMAGE;
    var title = add_store.isCaptured(url) ? ON_TITLE : OFF_TITLE;
    if (img.src.indexOf(src) == -1) {
      img.src = src;
    }
    if (img.title.indexOf(title) == -1) {
      img.title = title;
    }
  }
}

// Add or remove url from dynamic resource store and set image src appropriately - acts as a toggle
function toggleUrlFromStore(img, url) {
  if (isGoogleGearsEnabled(true)) {
    add_store.isCaptured(url) ? removeUrlFromStore(url) : addUrlToStore(url);
    //checkImageToggleforUrl(img, url);
    checkImages();
  }
}

// Add the url to the dynamic resource store and create managed store
function addUrlToManagedStore(url) {
  if (isGoogleGearsEnabled(true)) {
    createManagedStore();
    add_store.capture(url, addUrlCallback);
  }
}

// Add or remove url from dynamic resource store and create managed store and set image src appropriately - acts as a toggle
function toggleUrlFromManagedStore(img, url) {
  if (isGoogleGearsEnabled(true)) {
    add_store.isCaptured(url) ? removeUrlFromStore(url) : addUrlToManagedStore(url);
    //cacheStatus = img.id;
    //checkImageToggleforUrl(img, url);
    checkImages();
  }
}


