// Copyright 2009 Google Inc.  All Rights Reserved.

/**
 * @fileoverview Detecting user's root by url hasher to customize
 * call action copy iGoogle Showcase 
 * @author Zacky Ma
 */

var gweb = gweb || {};

gweb.hasher = function() {
  var hashParams = location.hash.substring(1).split('&');
  var hashObj = {};

  if (!(hashParams.length == 1 && hashParams[0] == '')) {
    for (var i = 0, j = hashParams.length; i < j; i++) {
      var key = hashParams[i].split('=')[0],
          value = hashParams[i].split('=')[1];

      hashObj[key] = value;
    }
  }

  function hasProperty(obj) {
    for (var i in obj) {
      return true;
    }
    return false;
  }

  return {
    'get' : function(key) {
      if (!hasProperty(hashObj)) {
        return null;
      }
      if (!key) {
        return hashObj;
      } else {
        if (!hashObj[key]) {
          return null;
        }
        return hashObj[key];
      }
    }
  };
}();

gweb.cookie = (function() {
  function create(name, value, days, path) {
    var exp = '';
    var cpath = (path && path != '') ? path : '/';

    if (days) {
      var date = new Date();

      date.setTime(date.getTime() + days * 86400000);
      exp = '; expires=' + date.toGMTString();
    } else {
      exp = '';
    }
    document.cookie = name + '=' + value + exp + '; path=' + path;
  }
  return {
    'make': create,
    'get' : function(name) {
      var cookies = document.cookie.split(';');
      for (var i = 0, j = cookies.length; i < j; i++) {
        if (cookies[i].indexOf(name + '=') != -1) {
          return cookies[i].split('=')[1];
        }
      }
      return null;
    },
    'delete' : function(name, path) {
      create(name, '', -1, path);
    }
  };
})();

if (!document.getElementById('asATab')) {
  var source = gweb.hasher.get('source');
  var path = location.pathname;

  path = path.substring(0, path.lastIndexOf('/') + 1);

  if (source) {
    gweb.cookie.make('IG_SHOWCASE', source, null, path);
  }
} else {
  var igSource = gweb.cookie.get('IG_SHOWCASE');

  if (igSource && igSource == 'ig') {
    document.getElementById('asATab').innerHTML = '&nbsp;as a tab';
  }
}
