/**
 * @fileoverview  Scripts for Street View microsite.
 * @author  Jeremy Weinstein (Jeremy Weinstein)
 */

/**
 * Initialize the svm namespace.
 */
var svm = {};


/**
 * A list of all locales this site is available in.
 */
svm.LOCALES = [
  ['pt-BR_br', 'Brasil'],
  ['en_ca', 'Canada (English)'],
  ['fr_ca', 'Canada (Français)'],
  ['cs_cz', 'Česká republika'],
  ['da_ALL', 'Dansk'],
  ['de_ALL', 'Deutschland'],
  ['es_ALL', 'España'],
  ['el_ALL', 'Ελλάδα'],
  ['fr_ALL', 'France'],
  ['en_ie', 'Ireland (English)'],
  ['ga_ie', 'Ireland (Gaeilge)'],
  ['it_ALL', 'Italia'],
  ['ja', '日本'],
  ['pt-PT_ALL', 'Portugal'],
  ['nl_ALL', 'Nederland'],
  ['no_ALL', 'Norge'],
  ['de_ch', 'Schweiz (Deutsch)'],
  ['it_ch', 'Svizzera (italiano)'],
  ['fr_ch', 'Suisse (Français)'],
  ['en_za', 'South Africa (English)'],
  ['af_za', 'Suid-Afrika (Afrikaans)'],
  ['zu_za', 'uMzansi Afrika (Zulu)'],
  ['fi_ALL', 'Suomi'],
  ['sv_ALL', 'Svenska'],
  ['zh-TW', '台灣'],
  ['zh-TW_hk','香港'],
  ['en_us', 'United States'],
  ['en_uk', 'United Kingdom']
];


/**
 * An object that can handle a feed and write some data.
 * @constructor
 * @param {string} divId The ID of the div element to write to.
 */
svm.feedWriter = function(divId) {
  this.divEl = document.getElementById(divId);
  this.feedData = '';
};


/**
 * Fills the contents of the div element with the feed data.
 */
svm.feedWriter.prototype.drawFeed = function() {
  this.divEl.innerHTML = this.feedData;
};


svm.feedWriter.prototype.handleBloggerFeed = function(json) {
  var output = '';

  for (var i = 0; i < 3; i++) {
    var postUrl;
    var entry = json.feed.entry[i]
    var postTitle = entry.title.$t;
    var postDate = entry.published.$t;
    postDate = postDate.substr(0, 10);

    for (var k = 0; k < entry.link.length; k++) {
      if (entry.link[k].rel == 'alternate') {
        postUrl = entry.link[k].href;
        break;
      }
    }
    output += '<li>' + postDate + ' - <a href="'+ postUrl +
      '" target="_blank">'+ postTitle + '</a>';
  }
  this.feedData = output;
  this.drawFeed();
};


svm.trixWriter = function(feedUrl) {
  this.feedUrl = feedUrl;
  this.feedData = {};
  this.wrapperEl = document.getElementById('cities');
  this.selectEl = document.getElementById('countries');
  this.countries = {};
  this.selectEl.onchange = this.handleSelect(this);
};


svm.trixWriter.prototype.handleSelect = function(me) {
  return function() {
    me.writeCitiesToTable(me.selectEl.options[me.selectEl.selectedIndex].value);
  }
};


svm.trixWriter.prototype.convertRowToCountryName = function(fullRow) {
  return fullRow.split(" (")[0];
};


svm.trixWriter.prototype.convertRowToParts = function(fullRow, part) {
  return fullRow.split(", ")[part];
};


svm.trixWriter.prototype.convertRowToColTitle = function(fullRow, part) {
  var regex = new RegExp('\\((.*)\\)');
  var results = regex.exec(fullRow);
  if (results != null) {
    return results[1].split(', ')[part];
  }
};


svm.trixWriter.prototype.isValidState = function(stateName) {
  if (stateName.indexOf('(') != -1) {
    return false;
  } else {
    return true;
  }
};


svm.trixWriter.prototype.initData = function(data, opt_defaultCountry) {
  for (var item in data) {
    var countryName = this.convertRowToCountryName(data[item].rowTitle);
    this.countries[countryName] = {};
    this.countries[countryName]['title'] = countryName;
    this.countries[countryName]['row_1'] =
        this.convertRowToColTitle(data[item].rowTitle, 0);
    this.countries[countryName]['row_2'] =
        this.convertRowToColTitle(data[item].rowTitle, 1);
    this.countries[countryName]['states'] = {};
    for (var moredata in data[item]) {
      var stateName = this.convertRowToParts(data[item][moredata], 0);
      if (this.isValidState(stateName)) {
        var cityName = this.convertRowToParts(data[item][moredata], 1);
        if (!this.countries[countryName]['states'][stateName]) {
          this.countries[countryName]['states'][stateName] = [];
        }
        this.countries[countryName]['states'][stateName].push(cityName);
      }
    }
  }
  if (opt_defaultCountry) {
    this.writeCountriesToSelect(opt_defaultCountry);
    this.writeCitiesToTable(opt_defaultCountry);
  } else {
    this.writeCountriesToSelect();
    this.writeCitiesToTable('Australia');
  }
};


svm.trixWriter.prototype.writeCountriesToSelect = function(opt_defaultCountry) {
  for (var country in this.countries) {
    if (country != 'undefined') {
      var childEl = document.createElement('option');
      childEl.innerHTML = country;
      if (country == opt_defaultCountry) {
        childEl.selected = 'selected';
      }
      childEl.value = country;
      this.selectEl.appendChild(childEl);
    }
  }
};


svm.trixWriter.prototype.writeCitiesToTable = function(countryName) {
  var new_table = '<table class="cities">' +
                  '<thead><th width="140">' +
                  this.countries[countryName]['row_1'] +
                  '</th><th>' +
                  this.countries[countryName]['row_2'] +
                  '</th></thead><tbody id="tbody">';
  var list = this.countries[countryName]['states'];
  for (var state in list) {
    var new_row = '<tr class="first"><td>' + state +
                  '</td><td>' + list[state].join(', ') +
                  '</td></tr>';
    new_table += new_row;
  }
  new_table += '</table>';
  this.wrapperEl.innerHTML = new_table;
};


svm.hoverTour = svm.hoverTour || {};

svm.hoverTour = function(config) {
  this.selectedScreenNum = config.selectedScreenNum;
  this.selectedHoverEl = document.getElementById(config.selectedThumbId);
  this.idPrefix = config.idPrefix;
  this.showScreen(this.selectedHoverEl, this.selectedScreenNum);
};


svm.hoverTour.prototype.showScreen = function(newHoverEl, newScreenNum) {
  this.selectedHoverEl.className = '';
  newHoverEl.className = 'selected';
  document.getElementById(this.idPrefix +
      this.selectedScreenNum).style.display = 'none';
  document.getElementById(this.idPrefix +
      newScreenNum).style.display = 'block';
  this.selectedScreenNum = newScreenNum;
  this.selectedHoverEl = newHoverEl;
};


/**
 * Constructor for the expander widget.
 * @param {Object} divId  The ID of the div element holding all of the items.
 */
svm.expander = function(divId) {
  this.list = document.getElementById(divId);
  this.list_items = this.list.getElementsByTagName('li');
  this.initItems();
};


/**
 * Initializes the items in the list sets expander properties.
 */
svm.expander.prototype.initItems = function() {
  for (var tag in this.list_items) {
    try {
      var a = this.list_items[tag].getElementsByTagName('a')[0];

      a.href = "javascript: void 0;";
      a.onclick = this.openHandler(this, this.list_items[tag]);

      if (this.list_items[tag].className == 'opened') {
        this.open(this.list_items[tag]);
      } else {
        this.list_items[tag].className = 'closed';
      }
    } catch(err) {}
  }
};


/**
 * Opens the list item.
 * @param {Object} li_to_expand  The list item to open.
 */
svm.expander.prototype.open = function(li_to_expand) {
  li_to_expand.className = 'opened';
  jQuery(li_to_expand.getElementsByTagName('div')[0]).slideDown('normal');
  li_to_expand.getElementsByTagName('a')[0].onclick =
      this.closeHandler(this, li_to_expand);
};


/**
 * Closes the list item.
 * @param {Object} li_to_expand  The list item to close.
 */
svm.expander.prototype.close = function(li_to_expand) {
  li_to_expand.className = 'closed';
  jQuery(li_to_expand.getElementsByTagName('div')[0]).slideUp('normal');
  li_to_expand.getElementsByTagName('a')[0].onclick =
      this.openHandler(this, li_to_expand);
};


/**
 * Handle to the open function.
 * @param {Object} li_to_expand  The list item to open.
 * @param {Object} me  The svm.expander object.
 */
svm.expander.prototype.openHandler = function(me, li_to_expand) {
  return function() {
    me.open(li_to_expand);
  }
};


/**
 * Handle to the close function.
 * @param {Object} li_to_expand  The list item to clos.
 * @param {Object} me  The svm.expander object.
 */
svm.expander.prototype.closeHandler = function(me, li_to_expand) {
  return function() {
    me.close(li_to_expand);
  }
};


svm.initLocaleList = function(defaultLocale) {
  // Populate the country selector with the list of launched locales.
  for (var i = 0, len = svm.LOCALES.length; i < len; i++) {
    if (defaultLocale == svm.LOCALES[i][0]) {
      var selected = ' selected';
    } else {
      var selected = '';
    }
    jQuery('<option' + selected + ' value="' + svm.LOCALES[i][0] + '">' +
        svm.LOCALES[i][1] + '</option>').appendTo(jQuery('#langsel'));
  }
};


/**
 * Perform this on page load.
 */
jQuery(document).ready(function() {
  jQuery('a').each(function() {
    var url = jQuery(this).attr('href');

    if (typeof(url) != 'undefined' && url.indexOf('http://') == 0) {
      var outgoingTag = url.toString();

      jQuery(this).attr("target", "_blank");
      jQuery(this).click(function() {
        pageTracker._trackEvent('Outgoing click', 'Auto-tagged', outgoingTag);
      });
    }
  });
});

