// Copyright 2009 Google Inc.  All Rights Reserved.

/**
 * @fileoverview Extensions for send to phone on mobile.google.com.
 *
 * Primarily controls the send to phone response behavior and UI.
 */

/**
 * @constructor
 */
var mgcErrorHook = function(conf) {
  var me = this;

  // Make sure the form has all the required elements to init STP.
  this.widget = conf.stpWidgetEl;
  this.widget.errorHook = function(){ me.showErrorWindow(); };
  this.widget.successHook = function(){ me.showSuccessWindow(); };
  this.widget.captchaHook = function(){ me.showErrorWindow(); };
  this.countryChangeHook = function(){ me.handleCountryChange(); };
  // Initialize this object.
  this.error_window_is_open = false;
  this.formEl = this.widget.formEl;
  this.$dialog = jQuery('#' + conf.dialogId);
  this.popupEl = document.getElementById(conf.popupId);
  this.error_contents = document.getElementById(conf.errorContentsId);
  this.collection = document.getElementById(conf.formContentsId);
  this.submitButtonEl = document.getElementById(conf.submitButtonId);
  this.formContentsId = conf.formContentsId;
  // Init a temporary placeholder to store the location of the collection.
  this.placeholder = document.createElement('div');
  this.collection.parentNode.insertBefore(this.placeholder, this.collection);
  // Link back to the main mgc session object.
  if (typeof(mgc_session) != 'undefined') {
    mgc_session.uio.stp_hook = this;
  }
};


/**
 * Changes the message text and message hash of the STP widget and also redraws
 * the page UI.
 */
mgcErrorHook.prototype.changeStpMessage = function(newMessageText, newMessageHash) {
  this.widget.setMessage(newMessageText, newMessageHash);
  jQuery('.stp-url').html(this.makeFriendlyUrl(this.widget.messageTextEl.value));
};


/**
 * Handler for what to do when the country selection changes.
 */
mgcErrorHook.prototype.handleCountryChange = function() {
  if (this.widget.countrySelectorEl.value != this.widget.countryDefault) {
    var new_country = this.widget.countrySelectorEl.value;
    var new_message = valid_messages[new_country][0];
    var new_hash = valid_messages[new_country][1];
    this.widget.setMessage(new_message, new_hash);
  } else {
    this.widget.setMessage(this.widget.config.messageText, this.widget.config.messageHash);
  }
  jQuery('.stp-url').html(this.makeFriendlyUrl(this.widget.messageTextEl.value));
};


/**
 * Set the width and height of the dialog background to the width and height of
 * the window.
 */
mgcErrorHook.prototype.openDialog = function() {
  var background = jQuery('<div class="stp-background"></div>');
  background.width($(document).width());
  background.height($(document).height());
  // Unhide the stp-windows and append them to the document body.
  jQuery(this.popupEl).width($(window).width());
  jQuery(this.popupEl).show();
  jQuery('body').append(background);
};


mgcErrorHook.prototype.closeDialog = function() {
  jQuery(this.popupEl).hide();
  jQuery('.stp-background').remove();
};


/**
 * Changes an "ugly" URL like http://m.google.com/search? to a "pretty"
 * URL like m.google.com/search
 * @param {string} uglyUrl An ugly URL.
 */
mgcErrorHook.prototype.makeFriendlyUrl = function(uglyUrl) {
  var new_url = uglyUrl.replace('http://','').replace(/\/\?.*$/, '');
  new_url = new_url.replace('http://','').replace(/\?.*$/, '');
  return new_url;
};


mgcErrorHook.prototype.showErrorWindow = function() {
  if (!this.error_window_is_open) {
    var me = this;
    jQuery(this.widget.errorWindowEl).show();
    this.openDialog();
    this.error_window_is_open = true;
    jQuery(this.error_contents).html('');
    jQuery(this.collection).appendTo(this.error_contents);
    var $new = jQuery(this.collection).clone().attr('id', this.collection.id + '_clone');
    $new.appendTo(this.placeholder);
    jQuery('#' + this.collection.id + '_clone' + ' input').each(function() {
      this.id = '';
      this.name = '';
    });
    this.submitButtonEl.onclick = this.widget.createPostHandler(this.widget);
    document.onkeydown = function(e) {
      if (e == null) {
        keycode = event.keyCode;
      } else {
        keycode = e.which;
      }
      if (keycode == 27) {
        me.hideErrorWindow();
      }
    };
  }
};

mgcErrorHook.prototype.hideSuccessWindow = function() {
  jQuery(this.widget.successWindowEl).hide();
  this.closeDialog();
};


mgcErrorHook.prototype.showSuccessWindow = function() {
  this.hideErrorWindow();

  var q = this.widget.successWindowEl;

  jQuery(this.popUpEl).append(q.parentNode.removeChild(q));
  this.popupEl.appendChild(q);
  if (this.widget.countrySelectorEl.value != this.widget.countryDefault) {
    jQuery('.stp-different-country').show();
  } else {
    jQuery('.stp-different-country').hide();
  }
  jQuery('.stp-url').html(this.makeFriendlyUrl(this.widget.messageTextEl.value));
  jQuery(this.widget.successWindowEl).show();
  this.openDialog();
};


mgcErrorHook.prototype.hideErrorWindow = function() {
  if (this.error_window_is_open) {
    this.error_window_is_open = false;
    jQuery(this.widget.errorWindowEl).hide();
    this.placeholder.innerHTML = '';
    this.placeholder.appendChild(this.collection);
    document.onkeydown = null;
  }
  this.closeDialog();
};

var valid_messages = {
  'au': ['http://m.google.com.au/?{dc:dc=[dc]}','AFXxHiAaSQPtH2WfzwUEoQslac15uIT-EQ'],
  'ar': ['http://m.google.com.ar/?{dc:dc=[dc]}','AFXxHiByqcBb_Kbkvjcfidu88Ylxd22k8g'],
  'at': ['http://m.google.at/?{dc:dc=[dc]}','AFXxHiB5rqk_OOjXv5_BA2OeY7VZud16EA'],
  'bd': ['http://m.google.bd/?{dc:dc=[dc]}','AFXxHiDKuNegwSFxV0S2q8U7lG0ztlvqSw'],
  'be': ['http://m.google.be/?{dc:dc=[dc]}','AFXxHiBYoZvfQSdr1oVbM0hhziOUn0ZhZg'],
  'bg': ['http://m.google.bg/?{dc:dc=[dc]}','AFXxHiA-LG4uH77L4kl-qqw1i-bjfrPWCg'],
  'br': ['http://m.google.com.br/?{dc:dc=[dc]}','AFXxHiBoycnFSqzob-cCeH-6wZ-HhUHUYA'],
  'ca': ['http://m.google.ca/?{dc:dc=[dc]}','AFXxHiDSqHDS6jfZu6lrjkYAQlcebBxR4Q'],
  'cl': ['http://m.google.cl/?{dc:dc=[dc]}','AFXxHiDfnJcQgWuvn7ra-QtJlrTuS7SeIw'],
  'cn': ['http://m.google.cn/?{dc:dc=[dc]}','AFXxHiDyWDVy7dvCmrxW81Sk8AzHwtevDQ'],
  'co': ['http://m.google.com.co/?{dc:dc=[dc]}','AFXxHiCRYohTTIs8nAiKR5NwESxyYeL6kw'],
  'hr': ['http://m.google.hr/?{dc:dc=[dc]}','AFXxHiB917ccNjwPiW0WY-gXdsu0riJ_bg'],
  'cz': ['http://m.google.cz/?{dc:dc=[dc]}','AFXxHiB1i01A-uMeDfW87cTcHTgr8HTf3g'],
  'de': ['http://m.google.de/?{dc:dc=[dc]}','AFXxHiAX9Nb4QDKUA4kFkTuhqvKSaIvoAg'],
  'dk': ['http://m.google.dk/?{dc:dc=[dc]}','AFXxHiAfB05V3If_3MuXE2nhqZuEWaXhQQ'],
  'eg': ['http://m.google.com.eg/?{dc:dc=[dc]}','AFXxHiAlatBULgbLO3QT1BTEvxgNMLTF9g'],
  'fi': ['http://m.google.fi/?{dc:dc=[dc]}','AFXxHiCEB7VwYDqOSkHX-9wd-QQTEpR_Mw'],
  'fr': ['http://m.google.fr/?{dc:dc=[dc]}','AFXxHiAY9oAuVUaadX4FKfn_dUgPHDESNQ'],
  'hk': ['http://m.google.hk/?{dc:dc=[dc]}','AFXxHiA4471WArwltAGc2FkfrwTdoSwXzw'],
  'hu': ['http://m.google.hu/?{dc:dc=[dc]}','AFXxHiCiQ5nuEp-eRUrroBtSrrimFJmJXg'],
  'id': ['http://m.google.co.id/?{dc:dc=[dc]}','AFXxHiCHMgITgxkd5S7kXqO1RoRPeZmw_g'],
  'ie': ['http://m.google.ie/?{dc:dc=[dc]}','AFXxHiC27LU_vcnjFB7W-_JJTOjVjCArzw'],
  'il': ['http://m.google.co.il/?{dc:dc=[dc]}','AFXxHiCX6sjREDGMnXV1E5OmXbFvQfTNkw'],
  'in': ['http://m.google.co.in/?{dc:dc=[dc]}','AFXxHiAgKv57dL9PH3tI1o27olirbAx1pA'],
  'it': ['http://m.google.it/?{dc:dc=[dc]}','AFXxHiCPDg_Mxkgc3eLzctAFD2-6y700kA'],
  'jp': ['http://m.google.co.jp/?{dc:dc=[dc]}','AFXxHiCt2HVAbTSpxYp2-clPeG8f_N23Kw'],
  'li': ['http://m.google.li/?{dc:dc=[dc]}','AFXxHiCcXApYpfyfP2e1GOnyj1AQLE88eg'],
  'ke': ['http://m.google.co.ke/?{dc:dc=[dc]}','AFXxHiDqIXwvfwsYJr0LQ2kMkUNiKRqaWA'],
  'ma': ['http://m.google.ma/?{dc:dc=[dc]}','AFXxHiB0SeQKwEebSK7p4dfIbIiy5K5JXA'],
  'mx': ['http://m.google.com.mx/?{dc:dc=[dc]}','AFXxHiCzDmzFOTPC7z4WG_DD0y30s7_1NQ'],
  'my': ['http://m.google.com.my/?{dc:dc=[dc]}','AFXxHiDd3FJo3MJhXgsXBwMY40NWCw4ufw'],
  'nl': ['http://m.google.nl/?{dc:dc=[dc]}','AFXxHiB7a1JDhVLBqm0WIG6B_yaXlHW0Yw'],
  'no': ['http://m.google.no/?{dc:dc=[dc]}','AFXxHiCqh4yA1pDT4mK25jOhcq9bVzBTDg'],
  'nz': ['http://m.google.co.nz/?{dc:dc=[dc]}','AFXxHiB6RODY9sxMpimvUaPJ1v3mD-VExg'],
  'pe': ['http://m.google.com.pe/?{dc:dc=[dc]}','AFXxHiD81770hQ-iXHIpk859bjmCQeQrKw'],
  'ph': ['http://m.google.ph/?{dc:dc=[dc]}','AFXxHiAaWfpEuU84iG-aEW5Nf8NJDq46mg'],
  'pk': ['http://m.google.pk/?{dc:dc=[dc]}','AFXxHiCGLrJoYnqpO4DCyWVurWaNwkaa9Q'],
  'pl': ['http://m.google.pl/?{dc:dc=[dc]}','AFXxHiCnLaqzDgKTheWd4ul8AQm45o3zSQ'],
  'pt': ['http://m.google.pt/?{dc:dc=[dc]}','AFXxHiB_fW80LSz3TTgcRX18nwdJxUZ5qA'],
  'ro': ['http://m.google.ro/?{dc:dc=[dc]}','AFXxHiB9jnlbSMLJd0bi_yjk0Eo8rdHAsg'],
  'ru': ['http://m.google.ru/?{dc:dc=[dc]}','AFXxHiCXLdYNbYZWVmHWW3bloFcuyjRHhg'],
  'sa': ['http://m.google.com.sa/?{dc:dc=[dc]}','AFXxHiAFjMOQTLs1spRHwVhouG4C7Mqb6Q'],
  'sg': ['http://m.google.sg/?{dc:dc=[dc]}','AFXxHiCgoiGOZWphPfUUVgyAWiGtW2Rz9g'],
  'es': ['http://m.google.es/?{dc:dc=[dc]}','AFXxHiBnSP-Qb4fDLY4aPaJjfxAddZhC4g'],
  'lk': ['http://m.google.lk/?{dc:dc=[dc]}','AFXxHiCCXof9UPOMr1gWlTzDcllhHzr5vA'],
  'se': ['http://m.google.se/?{dc:dc=[dc]}','AFXxHiBC4ApFcZ3m0lNP8dapGO7tecauPg'],
  'ch': ['http://m.google.ch/?{dc:dc=[dc]}','AFXxHiCEzGO7nXm6icgAxUArQRiVc40row'],
  'tw': ['http://m.google.tw/?{dc:dc=[dc]}','AFXxHiBajkgwOuNe_1eCDkjJxeQ_rhtc1w'],
  'gb': ['http://m.google.co.uk/?{dc:dc=[dc]}','AFXxHiAkgQAIt_YvSE3O0nRomg5LCyidOg'],
  'us': ['http://m.google.com/?{dc:dc=[dc]}','AFXxHiDSA9KU5Us3FOS04oN7aQyxkrA31w'],
  'za': ['http://m.google.co.za/?{dc:dc=[dc]}','AFXxHiC6EqOfTV4gCdrqOwX4wLCYe1vNcg']
};
