/**
 * @file select_or_other.js
 */

(function ($) {

  function select_or_other_check_and_show(ele, page_init) {
    var speed;
    if (page_init) {
      speed = 0;
    }
    else {
      speed = 200;
      ele = jQuery(ele).parents(".select-or-other")[0];
    }
    var $other_element = jQuery(ele).find(".select-or-other-other").parents("div.form-item").first();
    var $other_input = $other_element.find('input');
    if (jQuery(ele).find(".select-or-other-select option:selected[value=select_or_other], .select-or-other-select:checked[value=select_or_other]").length) {
      $.fn.prop ? $other_input.prop('required', true) : $other_input.attr('required', true)
      $other_element.show(speed, function() {
        if(!page_init) {
          $(this).find(".select-or-other-other").focus();
        }
      });
    }
    else {
      $other_element.hide(speed);
      $.fn.prop ? $other_input.prop('required', false) : $other_input.removeAttr('required');
      if (page_init)
      {
        // Special case, when the page is loaded, also apply 'display: none' in case it is
        // nested inside an element also hidden by jquery - such as a collapsed fieldset.
        jQuery(ele).find(".select-or-other-other").parents("div.form-item").first().css("display", "none");
      }
    }
  }

  /**
   * The Drupal behaviors for the Select (or other) field.
   */
  Drupal.behaviors.select_or_other = {
    attach: function(context) {
      jQuery(".select-or-other:not('.select-or-other-processed')", context)
        .addClass('select-or-other-processed')
        .each(function () {
          select_or_other_check_and_show(this, true);
        });
      jQuery(".select-or-other-select", context)
        .not("select")
        .click(function () {
          select_or_other_check_and_show(this, false);
        });
      jQuery("select.select-or-other-select", context)
        .change(function () {
          select_or_other_check_and_show(this, false);
        });
    }
  };

})(jQuery);
