text: // Generated by CoffeeScript 1.9.3
  (function() {
    var Instafeed;
  
    Instafeed = (function() {
      function Instafeed(params, context) {
        var option, value;
        this.options = {
          target: 'instafeed',
          resolution: 'thumbnail',
          sortBy: 'none',
          links: true,
          mock: false,
          useHttp: false
        };
        if (typeof params === 'object') {
          for (option in params) {
            value = params[option];
            this.options[option] = value;
          }
        }
        this.context = context != null ? context : this;
        this.unique = this._genKey();
      }
  
      Instafeed.prototype.run = function(url) {
        var header, instanceName, script;
        if (typeof this.options.clientId !== 'string') {
          throw new Error("Missing clientId.");
        }
        if (typeof this.options.userId !== 'string') {
          throw new Error("Missing userId.");
        }
        if ((this.options.before != null) && typeof this.options.before === 'function') {
          this.options.before.call(this);
        }
        if (typeof document !== "undefined" && document !== null) {
          script = document.createElement('script');
          script.id = 'instafeed-fetcher';
          script.src = url || this._buildUrl();
          header = document.getElementsByTagName('head');
          header[0].appendChild(script);
          instanceName = "instafeedCache" + this.unique;
          window[instanceName] = new Instafeed(this.options, this);
          window[instanceName].unique = this.unique;
        }
        return true;
      };
  
      Instafeed.prototype.parse = function(response) {
        var anchor, childNodeCount, childNodeIndex, childNodesArr, e, eMsg, fragment, header, htmlString, httpProtocol, i, image, imageObj, imageString, imageUrl, images, img, imgHeight, imgOrient, imgUrl, imgWidth, instanceName, j, k, len, len1, len2, node, parsedLimit, reverse, sortSettings, targetEl, tmpEl;
        if (typeof response !== 'object') {
          if ((this.options.error != null) && typeof this.options.error === 'function') {
            this.options.error.call(this, 'Invalid JSON data');
            return false;
          } else {
            throw new Error('Invalid JSON response');
          }
        }
        if (response.length === 0) {
          if ((this.options.error != null) && typeof this.options.error === 'function') {
            this.options.error.call(this, 'No images were returned from Instagram');
            return false;
          } else {
            throw new Error('No images were returned from Instagram');
          }
        }
        if ((this.options.success != null) && typeof this.options.success === 'function') {
          this.options.success.call(this, response);
        }
        if (this.options.sortBy !== 'none') {
          if (this.options.sortBy === 'random') {
            sortSettings = ['', 'random'];
          } else {
            sortSettings = this.options.sortBy.split('-');
          }
          reverse = sortSettings[0] === 'least' ? true : false;
          switch (sortSettings[1]) {
            case 'random':
              response.sort(function() {
                return 0.5 - Math.random();
              });
              break;
            case 'recent':
              response = this._sortBy(response, 'created_time', reverse);
              break;
            case 'liked':
              response = this._sortBy(response, 'likes.count', reverse);
              break;
            case 'commented':
              response = this._sortBy(response, 'comments.count', reverse);
              break;
            default:
              throw new Error("Invalid option for sortBy: '" + this.options.sortBy + "'.");
          }
        }
        if ((typeof document !== "undefined" && document !== null) && this.options.mock === false) {
          images = response;
          parsedLimit = parseInt(this.options.limit, 10);
          if ((this.options.limit != null) && images.length > parsedLimit) {
            images = images.slice(0, parsedLimit);
          }
          fragment = document.createDocumentFragment();
          if ((this.options.filter != null) && typeof this.options.filter === 'function') {
            images = this._filter(images, this.options.filter);
          }
          if ((this.options.template != null) && typeof this.options.template === 'string') {
            htmlString = '';
            imageString = '';
            imgUrl = '';
            tmpEl = document.createElement('div');
            for (i = 0, len = images.length; i < len; i++) {
              image = images[i];
              imageObj = image.images[this.options.resolution];
              if (typeof imageObj !== 'object') {
                eMsg = "No image found for resolution: " + this.options.resolution + ".";
                throw new Error(eMsg);
              }
              imgWidth = imageObj.width;
              imgHeight = imageObj.height;
              imgOrient = "square";
              if (imgWidth > imgHeight) {
                imgOrient = "landscape";
              }
              if (imgWidth < imgHeight) {
                imgOrient = "portrait";
              }
              imageUrl = imageObj.url;
              httpProtocol = window.location.protocol.indexOf("http") >= 0;
              if (httpProtocol && !this.options.useHttp) {
                imageUrl = imageUrl.replace(/https?:\/\//, '//');
              }
              imageString = this._makeTemplate(this.options.template, {
                model: image,
                id: image.id,
                link: image.link,
                type: image.type,
                image: imageUrl,
                width: imgWidth,
                height: imgHeight,
                orientation: imgOrient,
                caption: this._getObjectProperty(image, 'caption.text'),
                likes: image.likes.count,
                comments: image.comments.count,
                location: this._getObjectProperty(image, 'location.name')
              });
              htmlString += imageString;
            }
            tmpEl.innerHTML = htmlString;
            childNodesArr = [];
            childNodeIndex = 0;
            childNodeCount = tmpEl.childNodes.length;
            while (childNodeIndex < childNodeCount) {
              childNodesArr.push(tmpEl.childNodes[childNodeIndex]);
              childNodeIndex += 1;
            }
            for (j = 0, len1 = childNodesArr.length; j < len1; j++) {
              node = childNodesArr[j];
              fragment.appendChild(node);
            }
          } else {
            for (k = 0, len2 = images.length; k < len2; k++) {
              image = images[k];
              img = document.createElement('img');
              imageObj = image.images[this.options.resolution];
              if (typeof imageObj !== 'object') {
                eMsg = "No image found for resolution: " + this.options.resolution + ".";
                throw new Error(eMsg);
              }
              imageUrl = imageObj.url;
              httpProtocol = window.location.protocol.indexOf("http") >= 0;
              if (httpProtocol && !this.options.useHttp) {
                imageUrl = imageUrl.replace(/https?:\/\//, '//');
              }
              img.src = imageUrl;
              if (this.options.links === true) {
                anchor = document.createElement('a');
                anchor.href = image.link;
                anchor.appendChild(img);
                fragment.appendChild(anchor);
              } else {
                fragment.appendChild(img);
              }
            }
          }
          targetEl = this.options.target;
          if (typeof targetEl === 'string') {
            targetEl = document.getElementById(targetEl);
          }
          if (targetEl == null) {
            eMsg = "No element with id=\"" + this.options.target + "\" on page.";
            throw new Error(eMsg);
          }
          targetEl.appendChild(fragment);
          header = document.getElementsByTagName('head')[0];
          header.removeChild(document.getElementById('instafeed-fetcher'));
          instanceName = "instafeedCache" + this.unique;
          window[instanceName] = void 0;
          try {
            delete window[instanceName];
          } catch (_error) {
            e = _error;
          }
        }
        if ((this.options.after != null) && typeof this.options.after === 'function') {
          this.options.after.call(this);
        }
        return true;
      };
  
      Instafeed.prototype._buildUrl = function() {
        var base, final;
        base = "https://api2.bitsalad.co";
        final = base + "/feeds/" + this.options.clientId;
        final += "?ids=" + this.options.userId;
        final += "&callback=instafeedCache" + this.unique + ".parse";
        return final;
      };
  
      Instafeed.prototype._genKey = function() {
        var S4;
        S4 = function() {
          return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        };
        return "" + (S4()) + (S4()) + (S4()) + (S4());
      };
  
      Instafeed.prototype._makeTemplate = function(template, data) {
        var output, pattern, ref, varName, varValue;
        pattern = /(?:\{{2})([\w\[\]\.]+)(?:\}{2})/;
        output = template;
        while (pattern.test(output)) {
          varName = output.match(pattern)[1];
          varValue = (ref = this._getObjectProperty(data, varName)) != null ? ref : '';
          output = output.replace(pattern, function() {
            return "" + varValue;
          });
        }
        return output;
      };
  
      Instafeed.prototype._getObjectProperty = function(object, property) {
        var piece, pieces;
        property = property.replace(/\[(\w+)\]/g, '.$1');
        pieces = property.split('.');
        while (pieces.length) {
          piece = pieces.shift();
          if ((object != null) && piece in object) {
            object = object[piece];
          } else {
            return null;
          }
        }
        return object;
      };
  
      Instafeed.prototype._sortBy = function(data, property, reverse) {
        var sorter;
        sorter = function(a, b) {
          var valueA, valueB;
          valueA = this._getObjectProperty(a, property);
          valueB = this._getObjectProperty(b, property);
          if (reverse) {
            if (valueA > valueB) {
              return 1;
            } else {
              return -1;
            }
          }
          if (valueA < valueB) {
            return 1;
          } else {
            return -1;
          }
        };
        data.sort(sorter.bind(this));
        return data;
      };
  
      Instafeed.prototype._filter = function(images, filter) {
        var filteredImages, fn, i, image, len;
        filteredImages = [];
        fn = function(image) {
          if (filter(image)) {
            return filteredImages.push(image);
          }
        };
        for (i = 0, len = images.length; i < len; i++) {
          image = images[i];
          fn(image);
        }
        return filteredImages;
      };
  
      return Instafeed;
  
    })();
  
    (function(root, factory) {
      if (typeof define === 'function' && define.amd) {
        return define([], factory);
      } else if (typeof module === 'object' && module.exports) {
        return module.exports = factory();
      } else {
        return root.Instafeed = factory();
      }
    })(this, function() {
      return Instafeed;
    });
  
  }).call(this);
  