"use strict";
/*global Router,FormValidator,FormError*/
var EK = EK || {};
EK.OpportunityCorner = {
  routes: [{
    pattern: /^$/,
    action: function (hash) {
      EK.OpportunityCorner.Pages.show('.default-page');
      EK.OpportunityCorner.PostMyRequirementsForm.reset();
      EK.OpportunityCorner.DoneDeal.reset();
    }
  }, {
    pattern: /^post$/,
    action: function (hash) {
      EK.OpportunityCorner.PostMyRequirementsForm.show(hash);
    }
  }, {
    pattern: /^deal$/,
    action: function (hash) {
      EK.OpportunityCorner.DoneDeal.show(hash);
    }
  }, {
    pattern: /^participate(\?id=([\d]+))?$/,
    action: function (hash) {
      var id = hash.match(this.pattern)[2],
          data = $('#participate-button-' + id).get(0).onclick() || {};

      EK.OpportunityCorner.Participate.show(data);
    }
  }],
  init: function () {
    this.bind();
    Router.add(this.routes);
  },
  bind: function () {
    
  }
};
EK.OpportunityCorner.Pages = {
  init: function () {},
  hideAll: function () {
    $('.page').addClass('hidden');
  },
  show: function (selector) {
    this.hideAll();
    $('.page').filter(selector).removeClass('hidden');
  }
};
EK.OpportunityCorner.PostMyRequirementsForm = {
  errors: {
    firstNameLength: 'First Name should be more than 2 alphabetical chars',
    lastNameLength : 'Last Name should be more than 2 alphabetical chars',
    categoryLength: "You can't select more than 3 categories",
    categoryEmpty: "You should select at least one category"
  },
  init: function () {
    this.$form = $('#post-requirements-form');
    this.$errorContainer = $('#post-requirements-form-error');
    this.bind();

    EK.OpportunityCorner.PostMyRequirementsForm.MultiSelect.init();
  },
  show: function () {
    EK.OpportunityCorner.Pages.show('.requirements-form-page');
    this.switchToDefault();
  },
  bind: function () {
    var t = this;
    $('.deal_subm').live('click', function () {
      t.$form.trigger('submit');
    });

    this.$form.bindSubmit({
      beforeSubmit: function () {
        return t.beforeSubmit.call(t);
      },
      success: function () {
        t.switchToSuccess.call(t);
      }
    });

    $('.cr_anoth_listing').live('click', function () {
      t.show.call(t);
      t.$form.trigger('reset');
    });
  },
  beforeSubmit: function () {
    try {
      this.packMultiValue();
      this.checkFields();
      this.checkFirstName();
      this.checkLastName();
      this.checkEmail();
      this.checkConfirmEmail();
      this.checkPhone();
      this.checkCategoriesCount();
      this.hideErrors();
      EK.OpportunityCorner.PostMyRequirementsForm.MultiSelect.disable();
      return true;
    } catch (e) {
      this.showErrors(e);
      return false;
    }
  },
  hideErrors: function () {
    this.$errorContainer.hide();
  },
  showErrors: function (error) {
    FormValidator.showErrors(error, this.$errorContainer);
    this.$errorContainer.show();
  },
  checkFields: function () {
    var fields = {
      'first-name' : 'First Name',
      'last-name'  : 'Last Name',
      'email'      : 'Email Address',
      'confirm-email' : "Confirm Email Address",
      'phone' : 'Phone Number',
      'company-name' : 'Company Name',
      'what-company' : 'What kind of company are you',
      'annual-online-revenues' : 'Annual Online Revenues',
      'budget-range' : 'Budget range',
      'type-of-solution' : 'Type of Solution You Are Seeking',
      'decision-timeline-month' : 'Decision Timeline Month',
      'decision-timeline-year' : 'Decision Timeline Year'
    };
    FormValidator.checkFields(fields, '#post-requirements-form');
  },
  checkFirstName: function () {
    var firstName = this.getValue('first-name');
    FormValidator.checkName(firstName, this.errors.firstNameLength);
  },
  checkLastName: function () {
    var lastName = this.getValue('last-name');
    FormValidator.checkName(lastName, this.errors.lastNameLength);
  },
  checkEmail: function () {
    var email = this.getValue('email');
    FormValidator.checkEmail(email);
  },
  checkConfirmEmail: function () {
    var email = this.getValue('email'),
        confirmEmail = this.getValue('email');

    if (email !== confirmEmail) {
      throw new FormError("Email addresses do not match");
    }
  },
  checkCategoriesCount: function () {
    var count = EK.OpportunityCorner.PostMyRequirementsForm.MultiSelect.count();
    if (count > 3) {
      throw new FormError(this.errors.categoryLength);
    }
  },
  checkPhone: function () {
    var phone = this.getValue('phone');
    FormValidator.checkPhone(phone);
  },
  getValue: function (name) {
    return $.trim(this.$form.find('input[name=' + name + ']').val());
  },
  getSelectedValue: function (name) {
    return this.$form.find('*[name=' + name + ']').val();
  },
  getTextareaValue: function (name) {
    return $.trim(this.$form.find('textarea[name=' + name + ']').val());
  },
  packMultiValue: function () {
    EK.OpportunityCorner.PostMyRequirementsForm.MultiSelect.pack();
  },
  switchToSuccess: function () {
    var $el = $('#newdeal_view');
    $el.find('.default-state').hide();
    $el.find('.success-state').show();

    // show use input on success page
    // TODO: make this code elegant
    var fields = [
      'what-company',
      'annual-online-revenues',
      'decision-timeline-month',
      'decision-timeline-year',
      'budget-range',
      'type-of-solution',
      'challenges'
    ];

    var t = this;

    $.each(fields, function (index, item) {
      var value = t.getSelectedValue(item);
      if (value && typeof value === 'object') {
        value = value.join(', ');
      }
      $('#post-requirements-' + item + '-result').text(value);
    });

    var value = t.getTextareaValue('challenges');
    $('#post-requirements-challenges').text(value);
  },
  switchToDefault: function () {
    var $el = $('#newdeal_view');
    $el.find('.default-state').show();
    $el.find('.success-state').hide();
  },
  reset: function () {
    this.hideErrors();

    if (this.$form) {
      this.$form.trigger('reset');
    }
  }
};
EK.OpportunityCorner.PostMyRequirementsForm.MultiSelect = {
  init: function () {
    this.$el = $('#post-requirements-type-of-solution');
  },
  count: function () {
    var val = this.$el.val();
    return (val.constructor.toString().indexOf("Array") !== -1) ? val.length : 0;
  },
  pack: function () {
    var val = this.$el.find('option:selected').map(function () {
      return this.value;
    }).get().join(', ');
    $('#hidden-type-of-solution').val(val);
  },
  disable: function () {
    this.$el.attr('disabled', 'disabled');
  }
};
EK.OpportunityCorner.DoneDeal = {
  errors: {
    firstNameLength: 'First Name should be more than 2 alphabetical chars',
    lastNameLength : 'Last Name should be more than 2 alphabetical chars'  
  },
  init: function () {
    this.$form = $('#opp-corner-done-deal');
    this.$errorContainer = $('#done-deal-errors');
    this.bind();
  },
  show: function () {
	$('#opp-corner-done-deal')[0].reset();
    EK.OpportunityCorner.Pages.show('.deal-page');
    this.switchToDefault();
  },
  bind: function () {
    var t = this;

    this.$form.bindSubmit({
      beforeSubmit: function () {
        return t.beforeSubmit.call(t);
      },
      success: function () {
        t.switchToSuccess.call(t);
      }
    });
    this.$form.find('.submit').bind('click', function () {
      t.$form.trigger('submit');
    });
  },
  beforeSubmit: function () {
    try {
      this.checkFields();
      this.checkFirstName();
      this.checkLastName();
      this.checkEmail();
      this.checkPhone();
      this.hideErrors();
      return true;
    } catch (e) {
      this.showErrors(e);
      return false;
    }
  },
  checkFields: function () {
    var fields = {
      'first-name' : 'First Name',
      'last-name'  : 'Last Name',
      'email'      : 'Email Address',
      'phone' : 'Phone Number',
      'company' : 'Company Name',
      'title' : 'Title',
      'name-of-retailer' : 'Name of Retailer',
      'name-of-company-awarded-business' : 'Name of Company Awarded Business',
      'type-of-techology-or-solution-purchased' : 'Type of Technology or Solution Purchased',
      'details-about-chosen' : 'Details about how or why they were chosen'
      
    };
    FormValidator.checkFields(fields, '#opp-corner-done-deal');
  },
  checkFirstName: function () {
    var firstName = this.getValue('first-name');
    FormValidator.checkName(firstName, this.errors.firstNameLength);
  },
  checkLastName: function () {
    var lastName = this.getValue('last-name');
    FormValidator.checkName(lastName, this.errors.lastNameLength);
  },
  checkEmail: function () {
    var email = this.getValue('email');
    FormValidator.checkEmail(email);
  },
  checkPhone: function () {
    var phone = this.getValue('phone');
    FormValidator.checkPhone(phone);
  },
  getValue: function (name) {
    return $.trim(this.$form.find('input[name=' + name + ']').val());
  },
  hideErrors: function () {
    this.$errorContainer.hide();
  },
  showErrors: function (error) {
    FormValidator.showErrors(error, this.$errorContainer);
    this.$errorContainer.show();
  },
  
  switchToDefault: function () {
    var $el = $('.deal-page');
    $el.find('.default-state').show();
    $el.find('.success-state').hide();
    
  },
  switchToSuccess: function () {
    var $el = $('.deal-page');
    $el.find('.default-state').hide();
    $el.find('.success-state').show();
  },
  reset: function () {
    $('#add_donedeal').addClass('oppc_display').hide();
    if (this.$form) {
      this.$form.trigger('reset');
    }
  }
};
EK.OpportunityCorner.Participate = {
  init: function () {
    this.$container = $('#participate_view');
    this.$form = this.$container.find('form');
    this.$errorContainer = $('#request-participation-errors');
    this.bind();
  },
  bind: function () {
    var t = this;

    this.$form.bindSubmit({
      beforeSubmit: function () {
        return t.beforeSubmit.call(t);
      },
      success: function () {
        t.switchToSuccess.call(t);
      }
    });
    this.$form.find('.submit').bind('click', function () {
      t.$form.trigger('submit');
    });
  },
  show: function (data) {
    EK.OpportunityCorner.Pages.show('.request-participation-form-page');
    var message = !data.status 
      ? 'Thanks for raising your hand and proactively requesting to be included in this deal. Please complete the following.'
      : 'Thanks for raising your hand and proactively requesting to be included in this deal. Please complete the following.';

    $('#rpf-message').html(message);
    $('#deal_id').val(data.id);
    this.switchToDefault();
  },
  switchToDefault: function () {
    this.$container.find('.default-state').show();
    this.$container.find('.success-state').hide();
  },
  switchToSuccess: function () {
    this.$container.find('.default-state').hide();
    this.$container.find('.success-state').show();
  },
  beforeSubmit: function () {
    try {
      this.checkFields();
      this.checkEmail();
      this.checkPhone();
      this.hideErrors();
      return true;
    } catch (e) {
      this.showErrors(e);
      return false;
    }
  },
  checkFields: function () {
    var fields = {
      'first_name' : 'First Name',
      'last_name'  : 'Last Name',
      'email'      : 'Email Address',
      'phone' : 'Phone Number',
      'company' : 'Company Name',
      'title' : 'Title'
    };
    FormValidator.checkFields(fields, '#request-participation-form');
  },
  checkEmail: function () {
    var email = this.getValue('email');
    FormValidator.checkEmail(email);
  },
  checkPhone: function () {
    var phone = this.getValue('phone');
    FormValidator.checkPhone(phone);
  },
  getValue: function (name) {
    return $.trim(this.$form.find('input[name=' + name + ']').val());
  },
  hideErrors: function () {
    this.$errorContainer.hide();
  },
  showErrors: function (error) {
    FormValidator.showErrors(error, this.$errorContainer);
    this.$errorContainer.show();
  }
};
$(function () {
  if (/opportunity-corner/.test(window.location.pathname)) {
    EK.OpportunityCorner.init();
    EK.OpportunityCorner.Pages.init();
    EK.OpportunityCorner.DoneDeal.init();
    EK.OpportunityCorner.PostMyRequirementsForm.init();
    EK.OpportunityCorner.Participate.init();
  }
});

