// global flag to test for IE
window.isIE = (window.navigator.userAgent.indexOf("MSIE") != -1) || false;

// Gears util namespace
var gearsutil = {};

/*
 * Selectively turn on or off (using http://url/?__debug__ to turn on) 
 * console.log for debug.  Also create a virtual console.log() if it doesn't 
 * exist already (IE)
 */
function addConsoleDebug() {

  if (!/__debug__$/i.test(document.location.href)) {
    // non-debug mode, an empty function
    try {
      window.console = window.console || {};
      window.console.log = function(message) {};      
    } catch (e) {
    }

    return;
  }

  if (!window.console) {  
    
    window.debugMsgQueue = window.debugMsgQueue || [];
    
    // create the virtual window console  
    var divId = 'v_window_console';
    var consoleDiv = document.getElementById(divId);  
    if (!consoleDiv) {      
      var consoleDiv = document.createElement('div');
      consoleDiv.id = divId;
      consoleDiv.style.position = 'absolute';
      consoleDiv.style.top = '0';
      consoleDiv.style.right = '0';
      consoleDiv.onclick = function() {
        consoleDiv.innerHTML = '';
      };
    } 

    window.console = {};
    window.console.log = function(message) {
            
      // IE can sometimes throw an exception if document.body is accessed
      // before the document is fully loaded
      var body = null;        
      try {
          body = document.body;          
      } catch (e) {}

      if (body) {
        window.debugMsgQueue.push(message);  
        while (window.debugMsgQueue.length > 0) {
          var msg = window.debugMsgQueue.pop();
          var msgDiv = document.createElement('div');
          msgDiv.innerHTML = msg;
          consoleDiv.appendChild(msgDiv);         
        }

        // if consoleDiv still hasn't been added to the DOM tree
        if (consoleDiv.parentNode != body) {
          body.appendChild(consoleDiv);  
        }
      } else {
        // document.body not ready yet
        window.debugMsgQueue.push(message);         
      }
    };

  }       
}

function props(obj) {
  for (name in obj) {
    console.log(name + ' = ' + obj[name]);
  }
}

/**
 * This method dynamically loads a script from an URL via script tag injection
 * @param {string} url The URL of the script to be loaded
 * @param {Function} callback The callback method that will be invoked when
 *   loading is completed.
 */ 
function scriptLoad(url, callback) {

  var script = document.createElement('script');
  script.src = url;

  var heads = document.getElementsByTagName('head');

  if (heads.length > 0) {
    head = heads[0]; 
    head.appendChild(script);
  } else {
    head = document.createElement('head');    
    head.appendChild(script);
    document.body.parentNode.appendChild(head);
  }

  // most browsers
  script.onload = callback;  
  
  // IE 6 & 7
  script.onreadystatechange = function() {
    if (script.readyState == 'loaded' || script.readyState == 'complete') {
      callback();
    }
  };
}

gearsutil.isGearsInstalled = function() {

  // We are already defined. Hooray!
  if (window.google && google.gears) {
    return true;
  }

  var factory = null;

  // Firefox
  if (typeof GearsFactory != 'undefined') {
    factory = new GearsFactory();
  } else {
    // IE
    try {
      factory = new ActiveXObject('Gears.Factory');
    } catch (e) {
      // Safari
      if (navigator.mimeTypes["application/x-googlegears"]) {
        factory = document.createElement("object");
        factory.style.display = "none";
        factory.width = 0;
        factory.height = 0;
        factory.type = "application/x-googlegears";
        document.documentElement.appendChild(factory);
      }
    }
  }

  // *Do not* define any objects if Gears is not installed. This mimics the
  // behavior of Gears defining the objects in the future.
  if (!factory) {
    return false;
  }

  // Now set up the objects, being careful not to overwrite anything.
  if (!window.google) {
    window.google = {};
  }

  if (!google.gears) {
    google.gears = {factory: factory};
  }

  return true;
};

gearsutil.getGearsInstallURL = function(msg) {
  return "http://gears.google.com/?action=install&message=" + 
    msg + '&return=' + document.location.href;      
};

gearsutil.defaultNoGears = function(msg) {
  var installUrl = gearsutil.getGearsInstallURL(msg);

  var html = 'Sorry, this site requires the use of ' + 
    '<a href="http://code.google.com/apis/gears/">Google Gears</a>.<br><br>' +
    'Do you want to install Google Gears?&nbsp;&nbsp;';      

  var div = document.createElement('div');
  div.innerHTML = html;          

  var installButton = document.createElement('input');
  installButton.type = 'button';
  installButton.value = 'install';

  installButton.onclick = function() {
    document.location.href= installUrl;
  };

  div.appendChild(installButton);

  document.body.innerHTML = '';

  document.body.appendChild(div);
};

gearsutil.defaultNoPermission = function(msg) {
  var html = 'Sorry, this site requires the use of ' + 
    '<a href="http://code.google.com/apis/gears/">Google Gears</a>.' + 
    '<br><br>Do you want to grant the use of Google Gears API?&nbsp;&nbsp;';  

  var div = document.createElement('div');
  div.innerHTML = html;          

  var button = document.createElement('input');
  button.type = 'button';
  button.value = 'grant';

  button.onclick = function() {
    document.location.href = document.location.href;
  };

  div.appendChild(button);

  document.body.innerHTML = '';

  document.body.appendChild(div);
};

gearsutil.requestGearsForLocation = function(msg) {
  var success = false;
  if (gearsutil.isGearsInstalled()) {
    success = 
        google.gears.factory.create('beta.geolocation').
        getPermission(msg);   
  } 
  return success;
};

gearsutil.requestGearsForLocalStorage = function(msg) {
  var success = false;
  if (gearsutil.isGearsInstalled()) {
    success = google.gears.factory.getPermission(msg);   
  } 
  return success;
};

