var WalkieTalkie = {
  receiver : '#contact_us > div',
  sender : 'a.submit',
  successHTML : '<h2>You win the game.</h2><p>We look forward to a sweet high five with you!</p>',
  nerdColor : '<h2>Nice color nerd.</h2><p>We look forward to a sweet high five with you!</p>',

  required : {
    'email' : /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
    'name' : /\*/
  },

  batterize : function() {
    $("input, textarea").placeholder();
    this.monitor();
  },

  clarify : function(evnt) {
    var input = evnt.target;
    var className = input.className;
    var errorNode = $(input.nextElementSibling);

    var jInput = jQuery(input);
    if (!input.getAttribute('required')) return true;
    if (input.value.length < 1) {
      errorNode.addClass('error');
      return false;
    }
    if (jInput.hasClass('email') && !input.value.match(new RegExp(this.required['email']))) {
      errorNode.addClass('error');
      return false;
    }
    errorNode.removeClass('error');
    return true;
  },

  intercepted : function(err, status, response) {
    throw new Error("Your email was intercepted by spies! Oh Noes!!");
  },

  monitor : function() {
    this.receiver = jQuery(this.receiver);
    jQuery(this.receiver).children('').blur(this.clarify.bind(this));
    jQuery(this.sender).click(this.validate.bind(this));
  },

  roger : function() {
    var _data = {};
    this.receiver.children(':not(span)').each(function() {
      _data[this.className] = this.value;
      if (this.className === 'color' && this.value.match(/^#?(([a-fA-F0-9]){3}){1,2}$/)) {
        WalkieTalkie.successHTML = WalkieTalkie.nerdColor;
      }
    });
    this.transmit(_data);
  },

  success : function(data, status, response) {
    var _form = this.receiver.parent();
    _form.fadeOut(250, function() {
      _form.children('').remove();
      _form.append(this.successHTML);
      _form.fadeIn(250);
    }.bind(this));
  },

  transmit : function(data) {
    jQuery.ajax({
      type : 'POST',
      url : '/email',
      contentType : 'application/json',
      data : JSON.stringify(data),
      success : this.success.bind(this),
      error : this.intercepted.bind(this)
    });
  },

  validate : function() {
    var isValidName = this.clarify({target : this.receiver.find('.name')[0]});
    var isValidEmail = this.clarify({target : this.receiver.find('.email')[0]});
    if (isValidName && isValidEmail) {
      this.roger();
    }
    return false;
  }
};


jQuery(document).ready(WalkieTalkie.batterize.bind(WalkieTalkie));
