(function() {
  var colorSelectId = 'attribute75';

  var functionMethods = {
    deferUntil: function(condition) {
      this.interval = setInterval(function() {
        if (!condition()) return;
        clearInterval(this.interval);
        this();
      }.bind(this), 50);
    }
  };

  var change = function(event) {
    $$('.product-image-popup').invoke('hide');
    var option = $$('#attribute75 option').find(function(o) {
      return o.value == event.element().getValue();
    });
    var swatch = $$('.swatch').find(function(s) {
      return option.innerHTML == s.title.replace(/&/, '&amp;');
    });
    $('link_' + swatch.id).show();
  };

  var click = function(event) {
    $$('.product-image-popup').invoke('hide');
    $('link_' + event.element().id).show();
    var f = function() {
      var option = $$('option').find(function(o) {
        return o.innerHTML == event.element().title.replace(/&/, '&amp;');
      });
      $(colorSelectId).value = option.value;
    };
    Object.extend(f, functionMethods);
    f.deferUntil(function(){ return !$(colorSelectId).disabled });
  };

  Event.observe(window, 'load', function() {
    $$('.swatch').each(function(s) {
      s.setStyle({cursor: 'pointer'});
      s.observe('click', click);
    });
    if ($('attribute75')) {
      $('attribute75').observe('change', change);
    }
  });
})();

