// retina.js, a high-resolution image swapper (http://retinajs.com), v0.0.2

(function() {

  var root = (typeof exports == 'undefined' ? window : exports);



  root.Retina = Retina;

  function Retina() {}

  Retina.init = function(context) {
    if (context == null) context = root;

    var existing_onload = context.onload || new Function;

    context.onload = function() {
      var images = document.getElementsByTagName("img"), retinaImages = [], i, image;
      for (i = 0; i < images.length; i++) {
        image = images[i];
        retinaImages.push(new RetinaImage(image));
      }
      existing_onload();
    }
  };

  Retina.isRetina = function(){
    var mediaQuery = "(-webkit-min-device-pixel-ratio: 1.5),\
                      (min--moz-device-pixel-ratio: 1.5),\
                      (-o-min-device-pixel-ratio: 3/2),\
                      (min-resolution: 1.5dppx)";

    if (root.devicePixelRatio > 1)
      return true;

    if (root.matchMedia && root.matchMedia(mediaQuery).matches)
      return true;

    return false;
  };


  root.RetinaImagePath = RetinaImagePath;

  function RetinaImagePath(path) {
    this.path = path;
    this.at_2x_path = path.replace(/\.\w+$/, function(match) { return "@2x" + match; });
  }

  RetinaImagePath.confirmed_paths = [];

  RetinaImagePath.prototype.at_2x_path_loads = function(callback) {
    var variant = new Image();
    variant.onload  = function() { return callback(true);  }
    variant.onerror = function() { return callback(false); }
    variant.src = this.at_2x_path;
  }

  RetinaImagePath.prototype.check_2x_variant = function(callback) {
    var that = this;
    if (RetinaImagePath.confirmed_paths.indexOf(this.at_2x_path) != -1) {
      return callback(true);
    } else {
      this.at_2x_path_loads(function(wasLoaded) {
        if (wasLoaded) RetinaImagePath.confirmed_paths.push(that.at_2x_path);
        return callback(wasLoaded);
      });
    }
  }



  function RetinaImage(el) {
    this.el = el;
    this.path = new RetinaImagePath(this.el.getAttribute('src'));
    var that = this;
    this.path.check_2x_variant(function(hasVariant) {
      if (hasVariant) that.swap();
    });
  }

  root.RetinaImage = RetinaImage;

  RetinaImage.prototype.swap = function(path) {
    if (typeof path == 'undefined') path = this.path.at_2x_path;

    var that = this;
    function load() {
      if (! that.el.complete) {
        setTimeout(load, 5);
      } else {
        that.el.setAttribute('width', that.el.offsetWidth);
        that.el.setAttribute('height', that.el.offsetHeight);
        that.el.setAttribute('src', path);
      }
    }
    load();
  }




  if (Retina.isRetina()) {
    Retina.init(root);
  }

})();