
function storm_empty_select(_select) {
  if(_select == undefined) return;
  $(_select).html('');
};

function storm_fill_select(_select, _items, _with_all_option, _all_text) {
  var output = '';
  if(_with_all_option) {
    output += '<option value="0">' + _all_text + '</option>';
  }
  for (key in _items) {
    if (typeof _items[key] == 'string') {
      output += '<option value="' + key + '">' + _items[key] + '</option>';
    }
    else {
      output += '<optgroup label="' + key + '">' + storm_fill_select(undefined, _items[key], false, _all_text) + '</optgroup>';
    }
  }
  if(_select == undefined) return output;
  $(_select).html(output);
};

function storm_popup(sender, name, title, width, height, content_id, position) {
  var p_name = "storm" + name + '_popup';
  var p_close = "storm" + name + "_popup_close";

  var a = $(sender);
  var top = a.offset().top;
  var left = a.offset().left;

  switch (position) {
    case 'l':
      left = left-width;
    break;
    case 'lt':
      left = left - width;
      top = top - height;
    break;
    case 't':
      left = left - Math.floor(width / 2);
      top = top - height;
    break;
    case 'rt':
      top = top - height;
    break;
    case 'r':
    break;
    case 'rb':
    break;
    case 'b':
      left = left - Math.floor(width / 2);
    break;
    case 'lb':
      left = left-width;
    break;
  }

  $("#" + p_name).remove();
  var popup = '<div class="storm_popup" id="' + p_name + '">';
  popup += '<div class="storm_popup_title" id="' + p_close + '">' + title + '</div>';
  popup += '<div class="storm_popup_inner">';
  popup += $("#" + content_id).html();
  popup += "</div>";
  popup += "</div>";
  $("body").append(popup);
  var p = $("#" + p_name);
  p.css('position', 'absolute');
  p.css('top', top);
  p.css('left', left);
  p.css('width', width);
  p.css('height', height);
  p.show();
  $("#" + p_close).click(function(){
    $("#" + p_name).remove();
    return false;
  });
};

function storm_datext_tonull(sender, date_id) {
  if (sender.value == "-1") {
    $("#" + date_id + '-day').val("-1");
    $("#" + date_id + '-month').val("-1");
    $("#" + date_id + '-year').val("-1");
  }
};

(function ($) {
  Drupal.stormidea = Drupal.stormidea || {};
  Drupal.stormidea.dependent = {};

  Drupal.stormidea.dependent.bindings = {};
  Drupal.stormidea.dependent.activeBindings = {};
  Drupal.stormidea.dependent.activeTriggers = [];

  Drupal.stormidea.dependent.inArray = function(array, search_term) {
    var i = array.length;
    if (i > 0) {
     do {
      if (array[i] == search_term) {
         return true;
      }
     } while (i--);
    }
    return false;
  }


  Drupal.stormidea.dependent.autoAttach = function() {
    // Clear active bindings and triggers.
    for (i in Drupal.stormidea.dependent.activeTriggers) {
      jQuery(Drupal.stormidea.dependent.activeTriggers[i]).unbind('change');
    }
    Drupal.stormidea.dependent.activeTriggers = [];
    Drupal.stormidea.dependent.activeBindings = {};
    Drupal.stormidea.dependent.bindings = {};

    if (!Drupal.settings.stormidea) {
      return;
    }

    // Iterate through all relationships
    for (id in Drupal.settings.stormidea.dependent) {

      // Drupal.stormidea.dependent.activeBindings[id] is a boolean,
      // whether the binding is active or not.  Defaults to no.
      Drupal.stormidea.dependent.activeBindings[id] = 0;
      // Iterate through all possible values
      for(bind_id in Drupal.settings.stormidea.dependent[id].values) {
        // This creates a backward relationship.  The bind_id is the ID
        // of the element which needs to change in order for the id to hide or become shown.
        // The id is the ID of the item which will be conditionally hidden or shown.
        // Here we're setting the bindings for the bind
        // id to be an empty array if it doesn't already have bindings to it
        if (!Drupal.stormidea.dependent.bindings[bind_id]) {
          Drupal.stormidea.dependent.bindings[bind_id] = [];
        }
        // Add this ID
        Drupal.stormidea.dependent.bindings[bind_id].push(id);
        // Big long if statement.
        // Drupal.settings.stormidea.dependent[id].values[bind_id] holds the possible values

        if (bind_id.substring(0, 6) == 'radio:') {
          var trigger_id = "input[name='" + bind_id.substring(6) + "']";
        }
        else {
          var trigger_id = '#' + bind_id;
        }

        Drupal.stormidea.dependent.activeTriggers.push(trigger_id);


        var getValue = function(item, trigger) {
          if (item.substring(0, 6) == 'radio:') {
            var val = jQuery(trigger + ':checked').val();
          }
          else {
            switch (jQuery(trigger).attr('type')) {
              case 'checkbox':
                var val = jQuery(trigger).attr('checked') || 0;
                break;
              default:
                var val = jQuery(trigger).val();
            }
          }
          return val;
        }

        var setChangeTrigger = function(trigger_id, bind_id) {
          // Triggered when change() is clicked.
          var changeTrigger = function() {
            var val = getValue(bind_id, trigger_id);

            for (i in Drupal.stormidea.dependent.bindings[bind_id]) {
              var id = Drupal.stormidea.dependent.bindings[bind_id][i];

              // Fix numerous errors
              if (typeof id != 'string') {
                continue;
              }

              // This bit had to be rewritten a bit because two properties on the
              // same set caused the counter to go up and up and up.
              if (!Drupal.stormidea.dependent.activeBindings[id]) {
                Drupal.stormidea.dependent.activeBindings[id] = {};
              }

              if (Drupal.stormidea.dependent.inArray(Drupal.settings.stormidea.dependent[id].values[bind_id], val)) {
                Drupal.stormidea.dependent.activeBindings[id][bind_id] = 'bind';
              }
              else {
                delete Drupal.stormidea.dependent.activeBindings[id][bind_id];
              }

              var len = 0;
              for (i in Drupal.stormidea.dependent.activeBindings[id]) {
                len++;
              }

              var object = jQuery('#' + id + '-wrapper');
              if (!object.size()) {
                object = jQuery('#' + id).parent();
              }

              if (Drupal.settings.stormidea.dependent[id].type == 'disable') {
                if (Drupal.settings.stormidea.dependent[id].num <= len) {
                  // Show if the element if criteria is matched
                  object.attr('disabled', false);
                  object.children().attr('disabled', false);
                }
                else {
                  // Otherwise hide. Use css rather than hide() because hide()
                  // does not work if the item is already hidden, for example,
                  // in a collapsed fieldset.
                  object.attr('disabled', true);
                  object.children().attr('disabled', true);
                }
              }
              else {
                if (Drupal.settings.stormidea.dependent[id].num <= len) {
                  // Show if the element if criteria is matched
                  object.show(0);
                }
                else {
                  // Otherwise hide. Use css rather than hide() because hide()
                  // does not work if the item is already hidden, for example,
                  // in a collapsed fieldset.
                  object.css('display', 'none');
                }
              }
            }
          }

          jQuery(trigger_id).change(function() {
            // Trigger the internal change function
            // the attr('id') is used because closures are more confusing
            changeTrigger(trigger_id, bind_id);
          });
          // Trigger initial reaction
          changeTrigger(trigger_id, bind_id);
        }
        setChangeTrigger(trigger_id, bind_id);
      }
    }
  }

  Drupal.behaviors.stormideaDependent = function (context) {
    Drupal.stormidea.dependent.autoAttach();

    // Really large sets of fields are too slow with the above method, so this
    // is a sort of hacked one that's faster but much less flexible.
    $("select.stormidea-master-dependent:not(.stormidea-processed)")
      .addClass('stormidea-processed')
      .change(function() {
        var val = $(this).val();
        if (val == 'all') {
          $('.stormidea-dependent-all').show(0);
        }
        else {
          $('.stormidea-dependent-all').hide(0);
          $('.stormidea-dependent-' + val).show(0);
        }
      })
      .trigger('change');
  }
})(jQuery);
