"use strict";
/*global FormError*/
var EK = EK || {};

EK.CompanyAccount = {
  init: function () {
    this.initialized = true;
	this.bind();
  },
  bind: function () {
    var t = this;
    $('#add_solution').live('submit', function () {
      return t.submit.call(t);
    });

    $('#add_solution_btn').live('click', function () {
      $('#add_solution').trigger('submit');
    });
  },
  submit: function () {
    try {
      var name = $('input[name=name]').val();
      this.checkSolutionName(name);
      this.checkSolutionExists(name);
      $('#add_solution .slgl_errors_hold').hide();
    } catch (e) {
      $('#add_solution .slgl_error_title').html(e.message);
      $('#add_solution .slgl_errors_hold').show();
      return false;
    }
  },
  checkSolutionName: function (name) {
    if (!name) {
      throw new FormError('Please fill the Solution Name field.');
    }
    if (!/^(\d|\w){2,}/.test(name)) {
      throw new FormError('Please check a solution name. Name should contain at least two characters, cannot begin with a space or a punctuation mark.');
    }
  },
  checkSolutionExists: function (name) {
    var profile_id = $('input[name=provider_id]').val(),
        category_id = $('select[name=category_id]').val();

    $.ajax({
      type: 'POST',
      url: '/provider-directory/api/provider_data_value/exist_solution_name/',
      data: { profile_id: profile_id, category_id: category_id, solution_name: name },
      async: false,
      beforeSend: function () {
        $('#please_wait_dlg').modal();
      },
      success: function (xhr) {
        $.modal.close();
        if (xhr === 'true') {
          throw new FormError('A solution with this name already exists.');
        }
      },
      error: function () {
        $.modal.close();
      }
    });
  }
};
$(function () {
  if ((/^\/company-account/.test(window.location.pathname)) || (/provider-directory\/provider\/.*\/solutions/.test(window.location.pathname))) {
    EK.CompanyAccount.init();
  }
});
