// Copyright 2009 Google Inc.  All Rights Reserved.

/**
 * @fileoverview Namespace for Google Earth website.
 * @author Michal Drewniak
 */

/**
 * Namespace for Google Earth website.
 * @type {Object}
 */
var earth = {};

/**
 * Namespace for global variables used on the Earth website.
 * @type {Object}
 */
earth.globals = {};

/**
 * Trims leading and trailing spaces around a string.
 * @return {string} String without leading and trailing spaces.
 */
String.prototype.trim = function() {
  return this.replace(/^\s*|\s*$/, '');
};

/**
 * Takes user to appropriate download page based on the locale.
 * Function called when user clicks on the download button.
 */
earth.downloadEarth = function() {
  earth.download = new earth.Download();
  earth.download.chooseDownload();
};

/**
 * Stops default browser action.
 * @param {Event} e Event
 */
earth.stopDefault = function(e) {
  if (e && e.preventDefault) {
    e.preventDefault();
  } else {
    window.event.returnValue = false;
  }
};

/**
 *  Extracts variables from the url based on the specified delimeter.
 */
earth.parseURLVar = function() {
  var DELIMETERS = ['#', '\\?', '&'];
  var pipe = '|';
  var url = unescape(location.href);
  var arrURL = [];
  var vars = {};
  var tempVar = [];
  
  for (var i = 0; i < DELIMETERS.length; i++) {
    var regx = new RegExp(DELIMETERS[i], 'ig');
    url = url.replace(regx, pipe);
  }
  arrURL = url.split(pipe);
  
  for (var i = 1; i < arrURL.length; i++) {
    tempVar = arrURL[i].split('=');
    vars[tempVar[0]] = tempVar[1];
  }
  
  return vars;
};
    

/**
 * Extracts page id (relative url).
 * @return {string} Relative url path.
 */
earth.getPageId = function() {
  var pageId = location.pathname;
  pageId = pageId.replace(/\/?intl\/.*?\//i, '');
  pageId = pageId.replace(/\/?earth\//i, '');

  // Removes preceeding slash.
  if (pageId.charAt(0) == '/') {
    pageId = pageId.slice(1, pageId.length);
  }

  return pageId;
};

/**
 * Appends additional scripts to the end of the file.
 * @param {string} url URL of the script we're appending. Usually json feed.
 */
earth.appendScript = function(url) {
  var htmlTag = (document.getElementsByTagName('html'))[0];
  var scriptTag = document.createElement('script');
  scriptTag.src = url;
  scriptTag.type = 'text/javascript';
  htmlTag.appendChild(scriptTag);
};

/**
 * Extracts current locale info from language dropdown array.
 * @return {Object} object containing domain (.co.jp) and locale (ja).
 */
earth.getLocale = function() {
  if (earth.dropdown.locale) return earth.dropdown.locale;
  if (earth.globals.locale) return earth.globals.locale;

  var langsSize = goog.web.languages.length;

  // Example languages[i]: ['Dansk', '.com', 'da', false]
  for (var i = 0; i < langsSize; i++) {
    if (goog.web.languages[i][3]) {
      var locale = {};
      locale['domain'] = goog.web.languages[i][1];
      locale['lang'] = goog.web.languages[i][2];
      return locale;
    }
  }

  if (!locale) {
    var locale = {
      'domain': '.com',
      'lang': 'en'
    };
  }
  return locale;
};

/**
 * Adds tracking to specified element.
 * @param {Element} link Link to which we'll add onclick analytics tracking.
 * @param {string} analyticsId Analytics ID.
 * @param {string} locale Current locale.
 */
earth.addTracking = function(link, analyticsId, locale) {
  if (analyticsId) {
    link.onclick = function() {
      urchinTracker(analyticsId + '_' + locale);
    }
  }
};

/**
 * Executes tracking code.
 * @param {string} analyticsId Analytics ID.
 * @param {string} locale Current locale.
 */
earth.track = function(analyticsId, locale) {
  if (analyticsId) {
    urchinTracker(analyticsId + '_' + locale);
  }
};


/**
 * Dynamically localizes links to some outbound sites.
 */
earth.localizeLinks = function() {
  // English, do nothing
  if (earth.globals.locale['lang'] == 'en') {
    return;
  }

  /**
   * List of element ids which need to be localized.
   * 'element id' : 'type of the link (hl, intl)'
   * @type {Object}
   */
  var linkElements = {
    'linkSupport': '\?hl',
    'linkGallery': '&hl'
  };

  /**
   * Languages who's lang codes are different than those of the server.
   * 'lang + linkElements[el]': 'new lang'
   ' 'iw\?hl': 'he'
   */
  var langOverride = {
  };

  var lang = earth.globals.locale['lang'];

  for (var el in linkElements) {
    var currLink = document.getElementById(el);
    var overrideKey = lang + linkElements[el]

    if (linkElements[el] == '\?hl' || linkElements[el] == '&hl') {
      updateHl(currLink);
    } else {
      updateIntl();
    }
  }

  /**
   * Appends hl parameter to links.
   * @param {Element} currLink Currently parsed anchor.
   */
  function updateHl(currLink) {
    if (langOverride[overrideKey]) {
      // Update link with overridden locale info
      try {
        currLink.href += linkElements[el] + '=' + langOverride[overrideKey];
      } catch (e) {
        // Element doesn't exist.
      }
    } else if (currLink) {
      // Update link with currect locale info
      try {
        currLink.href += linkElements[el] + '=' + lang;
      } catch (e) {
        // Element doesn't exist.
      }
    }
  }

  /**
   * Appends or injects intl/xx directory into the path
   */
  function updateIntl() {
    // TODO: add code for changing intl links
  }
};


/**
 * Initializes functions used throughout Earth website.
 * Creates instances of objects used on the website.
 */
earth.setUp = function() {
  var pageId = earth.getPageId();
  earth.globals.pageId = earth.getPageId();

  earth.dropdown = new goog.web.LangDropdown();
  earth.globals.locale = earth.getLocale();

  earth.localizeLinks();

  switch (pageId) {
    case '':
      earth.hppromo = new earth.HomepagePromo('pcO-d8z1IPLrU43D0QCTWLA/od6');
      break;
    case 'index.html':
      earth.hppromo = new earth.HomepagePromo('pcO-d8z1IPLrU43D0QCTWLA/od6');
      break;
    case 'download-earth.html':
      earth.download = new earth.Download();
      earth.download.initDownloadPage();
      break;
    case 'download-earth-advanced.html':
      earth.download = new earth.Download();
      earth.download.initDownloadPage();
      break;
    case 'download-earth-pro.html':
      earth.download = new earth.Download();
      earth.download.initDownloadPage();
      break;
    case 'thanks.html':
      earth.download = new earth.Download();
      earth.download.thanksDownloadEarth();
      break;
    case 'tour.html':
      earth.tour = new earth.Tour();
      break;
    case 'geoeye/':
      earth.globals.apibuildings = false;
      earth.globals.apioverlay = 'http://mw2.google.com/mw-earth-vectordb/' +
          'geoeye/images/image_copyright_geoeye2009_v2.png';
      earth.earthapi = new earth.EarthAPI();
      initFilmstrip();
      break;
    case 'geoeye/index.html':
      earth.globals.apibuildings = false;
      earth.globals.apioverlay = 'http://mw2.google.com/mw-earth-vectordb/' +
          'geoeye/images/image_copyright_geoeye2009_v2.png';
      earth.earthapi = new earth.EarthAPI();
      initFilmstrip();
      break;
    case 'mars/giovanni.html':
      earth.marsLanding = new earth.LandingPage();
      break;
    case 'news/':
      earth.news = new earth.News();
      break;
    case 'news/index.html':
      earth.news = new earth.News();
      break;
  };
};

function changeLanguage(dropdown) {
  if (earth.dropdown) {
    earth.dropdown.changeLanguage(dropdown);
  }
}
