// Copyright 2009 Google Inc.
// Owner: webgroup-emea@google.com
// All Rights Reserved.

/**
 * @fileoverview JavaScript used for Transit landing page form
 * @author keekim@google.com (KeeKim Heng) with some edits
 * by amcgrath@google.com (Adam McGrath)
 */

(function() {

  var _start_address_message;
  var _destination_address_message;

  /**
   * CSS class name constants
   */
  var TLP_INPUT_CLASS = 'tlp-input';
  var TLP_INPUT_EMPTY_CLASS = 'tlp-input-empty';

  /**
   * Updates the date values and set the focus on the start input.
   * We add 2 minutes to the date and show 'Today' if we can.
   * Only set the date/time if the field values are unmodified, so
   * that we do not override values stored in browser history.
   * In no-timetable transit, there are no fdate and ftime elements,
   * so we need to check their validity.
   */
  function transitLandingPageOnloadHandler() {

    _start_address_message = tmap.SADDR;
    _destination_address_message = tmap.DADDR;

    var ftime = document.getElementById('ftime');
    var fdate = document.getElementById('fdate');
    var fstart = document.getElementById('saddr');
    var fdest = document.getElementById('daddr');
    var startDescription = document.getElementById('start_desc');
    var destDescription = document.getElementById('dest_desc');
    var transitForm = document.getElementById('transitForm');
    var vLink = document.getElementById('change-version');

    if (fdate && ftime) {

      var d = new Date;
      d.setTime(d.getTime() + 2 * 60 * 1000);

      var amPmFlag = tmap.US_FLAG;
      var defaultFormat = tmap.US_FLAG ? 'm/d/y' : 'd/m/y';      

      var formats = 'dmy dym mdy myd ydm ymd';
      var match = document.location.hash.match(/#(([dmy])([dmy])([dmy]))$/);

      if (vLink && match) {
        vLink.href += document.location.hash;
      }

      var dateFormat = match && formats.indexOf(match[1]) > -1 ?
      match[2] + '/' + match[3] + '/' + match[4] : defaultFormat;

      fdate.value = dateFormat.replace(/m/, (d.getMonth() + 1)).replace(/d/,
      d.getDate()).replace(/y/, (''+ (100 + (d.getYear() % 100))).substring(1));

      // Set the time to either [1-12]:MM am|pm or HH:MM 24hr format
      var mins = ('' + (100 + d.getMinutes())).substring(1);
      if (amPmFlag) {
        ftime.value = (((d.getHours() + 11) % 12) + 1) + ':' + mins +
          (d.getHours() >= 12 ? 'pm' : 'am');
      } else {
        ftime.value = ('' + (100 + d.getHours())).substring(1) + ':'
          + mins;
      }
    }

    // Add behaviour to the input fields.
    addFieldBehaviour(fstart, _start_address_message);
    addFieldBehaviour(fdest, _destination_address_message);

    // Add the onsubmit handler to the form's submit event.
    transitForm.onsubmit = createSubmitHandler(fstart, fdest);
  }

  /**
   * Creates and returns an onsubmit event handler function for the form.
   * @param {HTMLInputElement} fstart The start address element.
   * @param {HTMLInputElement} fdest The destination address element.
   * @return {Function} The event handler function.
   */
  function createSubmitHandler(fstart, fdest) {
    /**
     * On submit, if the address fields contain the descriptions
     * then clear them. Also, set the CSS class to the non-empty class,
     * since clicking back in Firefox doesn't trigger the onLoad event
     * and we don't want the text to be grey when a user returns.
     * @this Element
     */
    return function() {
      if (fstart.value == _start_address_message) {
        fstart.value = '';
        fstart.className = TLP_INPUT_CLASS;
      }
      if (fdest.value == _destination_address_message) {
        fdest.value = '';
        fdest.className = TLP_INPUT_CLASS;
      }
      return true;
    };
  }

  /**
   * Creates and returns an onfocus event handler function for the field.
   * @param {string} message The default message.
   * @return {Function} The event handler function.
   */
  function createFieldOnfocusHandler(message) {
    /**
     * On focus, if the content of the input is just the inplace label,
     * removes it and updates the style to be active.
     * @this Element
     */
    return function() {
      // Only change the class and remove the value if it is the default value.
      if (this.value == message) {
        this.className = TLP_INPUT_CLASS;
        this.value = '';
      }
    };
  }

  /**
   * Creates and returns an onblur event handler function for the field.
   * @param {string} message The default message.
   * @return {Function} The event handler function.
   */
  function createFieldOnblurHandler(message) {
    /**
     * On blur, if the field is empty, displays the inplace label and
     * updates the style to reflect that it's a label that is shown, not
     * actual content.
     * @this Element
     */
    return function() {
      // Only change the class and insert the default value if no value.
      if (this.value == '') {
        this.className = TLP_INPUT_EMPTY_CLASS;
        this.value = message;
      }
    };
  }

  /**
   * Adds behaviour to an input element so that when the element has no value,
   * a default message appears and the text changes is gray.
   * @param {HTMLInputElement} field The input element.
   * @param {string} message The default message.
   */
  function addFieldBehaviour(field, message) {
    // Check if the value is not the default message (for example, a cached
    // value appears in the text. If it is a user value, change the class.
    if (field.value != message) {
      field.className = TLP_INPUT_CLASS;
    }

    // Check if the value is empty - if it is, add the default text.
    if (field.value == '') {
      field.className = TLP_INPUT_EMPTY_CLASS;
      field.value = message;
    }
    field.onfocus = createFieldOnfocusHandler(message);
    field.onblur = createFieldOnblurHandler(message);
  }

  window.transitLandingPageOnloadHandler = transitLandingPageOnloadHandler;

})();

