
/**
 * Cloudinary's JavaScript library - Version 2.5.0
 * Copyright Cloudinary
 * see https://github.com/cloudinary/cloudinary_js
 *
 */
var slice = [].slice,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

(function(root, factory) {
  var name, ref, results, value;
  if ((typeof define === 'function') && define.amd) {
    return define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    return module.exports = factory(require('jquery'));
  } else {
    root.cloudinary || (root.cloudinary = {});
    ref = factory(jQuery);
    results = [];
    for (name in ref) {
      value = ref[name];
      results.push(root.cloudinary[name] = value);
    }
    return results;
  }
})(this, function(jQuery) {

  /*
   * Includes common utility methods and shims
   */

  /**
   * Return true if all items in list are strings
   * @function Util.allString
   * @param {Array} list - an array of items
   */
  var ArrayParam, BaseUtil, ClientHintsMetaTag, Cloudinary, CloudinaryJQuery, Condition, Configuration, Expression, ExpressionParam, FetchLayer, HtmlTag, ImageTag, Layer, LayerParam, Param, RangeParam, RawParam, SubtitlesLayer, TextLayer, Transformation, TransformationBase, TransformationParam, Util, VideoTag, addClass, allStrings, base64Encode, base64EncodeURL, camelCase, cloneDeep, cloudinary, compact, contains, convertKeys, crc32, defaults, difference, funcTag, functions, getAttribute, getData, hasClass, identity, isEmpty, isFunction, isNumberLike, isObject, isString, m, merge, objToString, objectProto, parameters, reWords, removeAttribute, setAttribute, setAttributes, setData, smartEscape, snakeCase, utf8_encode, webp, width, withCamelCaseKeys, withSnakeCaseKeys, without;
  allStrings = function(list) {
    var item, j, len;
    for (j = 0, len = list.length; j < len; j++) {
      item = list[j];
      if (!Util.isString(item)) {
        return false;
      }
    }
    return true;
  };

  /**
  * Creates a new array without the given item.
  * @function Util.without
  * @param {Array} array - original array
  * @param {*} item - the item to exclude from the new array
  * @return {Array} a new array made of the original array's items except for `item`
   */
  without = function(array, item) {
    var i, length, newArray;
    newArray = [];
    i = -1;
    length = array.length;
    while (++i < length) {
      if (array[i] !== item) {
        newArray.push(array[i]);
      }
    }
    return newArray;
  };

  /**
  * Return true is value is a number or a string representation of a number.
  * @function Util.isNumberLike
  * @param {*} value
  * @returns {boolean} true if value is a number
  * @example
  *    Util.isNumber(0) // true
  *    Util.isNumber("1.3") // true
  *    Util.isNumber("") // false
  *    Util.isNumber(undefined) // false
   */
  isNumberLike = function(value) {
    return (value != null) && !isNaN(parseFloat(value));
  };

  /**
   * Escape all characters matching unsafe in the given string
   * @function Util.smartEscape
   * @param {string} string - source string to escape
   * @param {RegExp} unsafe - characters that must be escaped
   * @return {string} escaped string
   */
  smartEscape = function(string, unsafe) {
    if (unsafe == null) {
      unsafe = /([^a-zA-Z0-9_.\-\/:]+)/g;
    }
    return string.replace(unsafe, function(match) {
      return match.split("").map(function(c) {
        return "%" + c.charCodeAt(0).toString(16).toUpperCase();
      }).join("");
    });
  };

  /**
   * Assign values from sources if they are not defined in the destination.
   * Once a value is set it does not change
   * @function Util.defaults
   * @param {Object} destination - the object to assign defaults to
   * @param {...Object} source - the source object(s) to assign defaults from
   * @return {Object} destination after it was modified
   */
  defaults = function() {
    var destination, sources;
    destination = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : [];
    return sources.reduce(function(dest, source) {
      var key, value;
      for (key in source) {
        value = source[key];
        if (dest[key] === void 0) {
          dest[key] = value;
        }
      }
      return dest;
    }, destination);
  };

  /*********** lodash functions */
  objectProto = Object.prototype;

  /**
   * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
   * of values.
   */
  objToString = objectProto.toString;

  /**
   * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
   * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
   *
   * @param {*} value The value to check.
   * @returns {boolean} Returns `true` if `value` is an object, else `false`.
   * @example
   *
  #isObject({});
   * // => true
   *
  #isObject([1, 2, 3]);
   * // => true
   *
  #isObject(1);
   * // => false
   */
  isObject = function(value) {
    var type;
    type = typeof value;
    return !!value && (type === 'object' || type === 'function');
  };
  funcTag = '[object Function]';

  /**
  * Checks if `value` is classified as a `Function` object.
  * @function Util.isFunction
  * @param {*} value The value to check.
  * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  * @example
  *
  * function Foo(){};  
  * isFunction(Foo);
  * // => true
  *
  * isFunction(/abc/);
  * // => false
   */
  isFunction = function(value) {
    return isObject(value) && objToString.call(value) === funcTag;
  };

  /*********** lodash functions */

  /** Used to match words to create compound words. */
  reWords = (function() {
    var lower, upper;
    upper = '[A-Z]';
    lower = '[a-z]+';
    return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');
  })();

  /**
  * Convert string to camelCase
  * @function Util.camelCase
  * @param {string} string - the string to convert
  * @return {string} in camelCase format
   */
  camelCase = function(source) {
    var i, word, words;
    words = source.match(reWords);
    words = (function() {
      var j, len, results;
      results = [];
      for (i = j = 0, len = words.length; j < len; i = ++j) {
        word = words[i];
        word = word.toLocaleLowerCase();
        if (i) {
          results.push(word.charAt(0).toLocaleUpperCase() + word.slice(1));
        } else {
          results.push(word);
        }
      }
      return results;
    })();
    return words.join('');
  };

  /**
   * Convert string to snake_case
   * @function Util.snakeCase
   * @param {string} string - the string to convert
   * @return {string} in snake_case format
   */
  snakeCase = function(source) {
    var i, word, words;
    words = source.match(reWords);
    words = (function() {
      var j, len, results;
      results = [];
      for (i = j = 0, len = words.length; j < len; i = ++j) {
        word = words[i];
        results.push(word.toLocaleLowerCase());
      }
      return results;
    })();
    return words.join('_');
  };
  convertKeys = function(source, converter) {
    var key, result, value;
    if (converter == null) {
      converter = Util.identity;
    }
    result = {};
    for (key in source) {
      value = source[key];
      key = converter(key);
      if (!Util.isEmpty(key)) {
        result[key] = value;
      }
    }
    return result;
  };

  /**
   * Create a copy of the source object with all keys in camelCase
   * @function Util.withCamelCaseKeys
   * @param {Object} value - the object to copy
   * @return {Object} a new object
   */
  withCamelCaseKeys = function(source) {
    return convertKeys(source, Util.camelCase);
  };

  /**
   * Create a copy of the source object with all keys in snake_case
   * @function Util.withSnakeCaseKeys
   * @param {Object} value - the object to copy
   * @return {Object} a new object
   */
  withSnakeCaseKeys = function(source) {
    return convertKeys(source, Util.snakeCase);
  };
  base64Encode = typeof btoa !== 'undefined' && isFunction(btoa) ? btoa : typeof Buffer !== 'undefined' && isFunction(Buffer) ? function(input) {
    if (!(input instanceof Buffer)) {
      input = new Buffer.from(String(input), 'binary');
    }
    return input.toString('base64');
  } : function(input) {
    throw new Error("No base64 encoding function found");
  };

  /**
  * Returns the Base64-decoded version of url.<br>
  * This method delegates to `btoa` if present. Otherwise it tries `Buffer`.
  * @function Util.base64EncodeURL
  * @param {string} url - the url to encode. the value is URIdecoded and then re-encoded before converting to base64 representation
  * @return {string} the base64 representation of the URL
   */
  base64EncodeURL = function(input) {
    var error1, ignore;
    try {
      input = decodeURI(input);
    } catch (error1) {
      ignore = error1;
    }
    input = encodeURI(input);
    return base64Encode(input);
  };
  BaseUtil = {
    allStrings: allStrings,
    camelCase: camelCase,
    convertKeys: convertKeys,
    defaults: defaults,
    snakeCase: snakeCase,
    without: without,
    isFunction: isFunction,
    isNumberLike: isNumberLike,
    smartEscape: smartEscape,
    withCamelCaseKeys: withCamelCaseKeys,
    withSnakeCaseKeys: withSnakeCaseKeys,
    base64EncodeURL: base64EncodeURL
  };

  /**
    * Includes utility methods and lodash / jQuery shims
   */

  /**
    * Get data from the DOM element.
    *
    * This method will use jQuery's `data()` method if it is available, otherwise it will get the `data-` attribute
    * @param {Element} element - the element to get the data from
    * @param {string} name - the name of the data item
    * @returns the value associated with the `name`
    * @function Util.getData
   */
  getData = function(element, name) {
    return jQuery(element).data(name);
  };

  /**
    * Set data in the DOM element.
    *
    * This method will use jQuery's `data()` method if it is available, otherwise it will set the `data-` attribute
    * @function Util.setData
    * @param {Element} element - the element to set the data in
    * @param {string} name - the name of the data item
    * @param {*} value - the value to be set
    *
   */
  setData = function(element, name, value) {
    return jQuery(element).data(name, value);
  };

  /**
    * Get attribute from the DOM element.
    *
    * This method will use jQuery's `attr()` method if it is available, otherwise it will get the attribute directly
    * @function Util.getAttribute
    * @param {Element} element - the element to set the attribute for
    * @param {string} name - the name of the attribute
    * @returns {*} the value of the attribute
    *
   */
  getAttribute = function(element, name) {
    return jQuery(element).attr(name);
  };

  /**
    * Set attribute in the DOM element.
    *
    * This method will use jQuery's `attr()` method if it is available, otherwise it will set the attribute directly
    * @function Util.setAttribute
    * @param {Element} element - the element to set the attribute for
    * @param {string} name - the name of the attribute
    * @param {*} value - the value to be set
   */
  setAttribute = function(element, name, value) {
    return jQuery(element).attr(name, value);
  };

  /**
   * Remove an attribute in the DOM element.
   *
   * @function Util.removeAttribute
   * @param {Element} element - the element to set the attribute for
   * @param {string} name - the name of the attribute
   */
  removeAttribute = function(element, name) {
    return jQuery(element).removeAttr(name);
  };

  /**
    * Set a group of attributes to the element
    * @function Util.setAttributes
    * @param {Element} element - the element to set the attributes for
    * @param {Object} attributes - a hash of attribute names and values
   */
  setAttributes = function(element, attributes) {
    return jQuery(element).attr(attributes);
  };

  /**
    * Checks if element has a css class
    * @function Util.hasClass
    * @param {Element} element - the element to check
    * @param {string} name - the class name
    @returns {boolean} true if the element has the class
   */
  hasClass = function(element, name) {
    return jQuery(element).hasClass(name);
  };

  /**
    * Add class to the element
    * @function Util.addClass
    * @param {Element} element - the element
    * @param {string} name - the class name to add
   */
  addClass = function(element, name) {
    return jQuery(element).addClass(name);
  };
  width = function(element) {
    return jQuery(element).width();
  };

  /**
   * Returns true if item is empty:
   * <ul>
   *   <li>item is null or undefined</li>
   *   <li>item is an array or string of length 0</li>
   *   <li>item is an object with no keys</li>
   * </ul>
   * @function Util.isEmpty
   * @param item
   * @returns {boolean} true if item is empty
   */
  isEmpty = function(item) {
    return (item == null) || (jQuery.isArray(item) || Util.isString(item)) && item.length === 0 || (jQuery.isPlainObject(item) && jQuery.isEmptyObject(item));
  };

  /**
   * Returns true if item is a string
   * @param item
   * @returns {boolean} true if item is a string
   */
  isString = function(item) {
    return typeof item === 'string' || (item != null ? item.toString() : void 0) === '[object String]';
  };

  /**
   * Recursively assign source properties to destination
   * @function Util.merge
   * @param {Object} destination - the object to assign to
   * @param {...Object} [sources] The source objects.
   */
  merge = function() {
    var args, i;
    args = (function() {
      var j, len, results;
      results = [];
      for (j = 0, len = arguments.length; j < len; j++) {
        i = arguments[j];
        results.push(i);
      }
      return results;
    }).apply(this, arguments);
    args.unshift(true);
    return jQuery.extend.apply(this, args);
  };

  /**
   * Creates a new array from the parameter with "falsey" values removed
   * @function Util.compact
   * @param {Array} array - the array to remove values from
   * @return {Array} a new array without falsey values
   */
  compact = function(arr) {
    var item, j, len, results;
    results = [];
    for (j = 0, len = arr.length; j < len; j++) {
      item = arr[j];
      if (item) {
        results.push(item);
      }
    }
    return results;
  };

  /**
   * Create a new copy of the given object, including all internal objects.
   * @function Util.cloneDeep
   * @param {Object} value - the object to clone
   * @return {Object} a new deep copy of the object
   */
  cloneDeep = function() {
    var args;
    args = jQuery.makeArray(arguments);
    args.unshift({});
    args.unshift(true);
    return jQuery.extend.apply(this, args);
  };

  /**
   * Check if a given item is included in the given array
   * @function Util.contains
   * @param {Array} array - the array to search in
   * @param {*} item - the item to search for
   * @return {boolean} true if the item is included in the array
   */
  contains = function(arr, item) {
    var i, j, len;
    for (j = 0, len = arr.length; j < len; j++) {
      i = arr[j];
      if (i === item) {
        return true;
      }
    }
    return false;
  };

  /**
   * Returns values in the given array that are not included in the other array
   * @function Util.difference
   * @param {Array} arr - the array to select from
   * @param {Array} values - values to filter from arr
   * @return {Array} the filtered values
   */
  difference = function(arr, values) {
    var item, j, len, results;
    results = [];
    for (j = 0, len = arr.length; j < len; j++) {
      item = arr[j];
      if (!contains(values, item)) {
        results.push(item);
      }
    }
    return results;
  };

  /**
   * Returns a list of all the function names in obj
   * @function Util.functions
   * @param {Object} object - the object to inspect
   * @return {Array} a list of functions of object
   */
  functions = function(object) {
    var i, results;
    results = [];
    for (i in object) {
      if (jQuery.isFunction(object[i])) {
        results.push(i);
      }
    }
    return results;
  };

  /**
   * Returns the provided value. This functions is used as a default predicate function.
   * @function Util.identity
   * @param {*} value
   * @return {*} the provided value
   */
  identity = function(value) {
    return value;
  };

  /**
   * @class Util
   */
  Util = jQuery.extend(BaseUtil, {
    hasClass: hasClass,
    addClass: addClass,
    getAttribute: getAttribute,
    setAttribute: setAttribute,
    removeAttribute: removeAttribute,
    setAttributes: setAttributes,
    getData: getData,
    setData: setData,
    width: width,
    isString: isString,
    isArray: jQuery.isArray,
    isEmpty: isEmpty,

    /**
     * Assign source properties to destination.
     * If the property is an object it is assigned as a whole, overriding the destination object.
     * @function Util.assign
     * @param {Object} destination - the object to assign to
     */
    assign: jQuery.extend,
    merge: merge,
    cloneDeep: cloneDeep,
    compact: compact,
    contains: contains,
    difference: difference,
    functions: functions,
    identity: identity,
    isPlainObject: jQuery.isPlainObject,

    /**
     * Remove leading or trailing spaces from text
     * @function Util.trim
     * @param {string} text
     * @return {string} the `text` without leading or trailing spaces
     */
    trim: jQuery.trim
  });

  /**
   * UTF8 encoder
   *
   */
  utf8_encode = function(argString) {
    var c1, enc, end, n, start, string, stringl, utftext;
    if (argString === null || typeof argString === 'undefined') {
      return '';
    }
    string = argString + '';
    utftext = '';
    start = void 0;
    end = void 0;
    stringl = 0;
    start = end = 0;
    stringl = string.length;
    n = 0;
    while (n < stringl) {
      c1 = string.charCodeAt(n);
      enc = null;
      if (c1 < 128) {
        end++;
      } else if (c1 > 127 && c1 < 2048) {
        enc = String.fromCharCode(c1 >> 6 | 192, c1 & 63 | 128);
      } else {
        enc = String.fromCharCode(c1 >> 12 | 224, c1 >> 6 & 63 | 128, c1 & 63 | 128);
      }
      if (enc !== null) {
        if (end > start) {
          utftext += string.slice(start, end);
        }
        utftext += enc;
        start = end = n + 1;
      }
      n++;
    }
    if (end > start) {
      utftext += string.slice(start, stringl);
    }
    return utftext;
  };

  /**
   * CRC32 calculator
   * Depends on 'utf8_encode'
   */
  crc32 = function(str) {
    var crc, i, iTop, table, x, y;
    str = utf8_encode(str);
    table = '00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D';
    crc = 0;
    x = 0;
    y = 0;
    crc = crc ^ -1;
    i = 0;
    iTop = str.length;
    while (i < iTop) {
      y = (crc ^ str.charCodeAt(i)) & 0xFF;
      x = '0x' + table.substr(y * 9, 8);
      crc = crc >>> 8 ^ x;
      i++;
    }
    crc = crc ^ -1;
    if (crc < 0) {
      crc += 4294967296;
    }
    return crc;
  };
  Layer = (function() {

    /**
     * Layer
     * @constructor Layer
     * @param {Object} options - layer parameters
     */
    function Layer(options) {
      this.options = {};
      if (options != null) {
        ["resourceType", "type", "publicId", "format"].forEach((function(_this) {
          return function(key) {
            var ref;
            return _this.options[key] = (ref = options[key]) != null ? ref : options[Util.snakeCase(key)];
          };
        })(this));
      }
    }

    Layer.prototype.resourceType = function(value) {
      this.options.resourceType = value;
      return this;
    };

    Layer.prototype.type = function(value) {
      this.options.type = value;
      return this;
    };

    Layer.prototype.publicId = function(value) {
      this.options.publicId = value;
      return this;
    };


    /**
     * Get the public ID, formatted for layer parameter
     * @function Layer#getPublicId
     * @return {String} public ID
     */

    Layer.prototype.getPublicId = function() {
      var ref;
      return (ref = this.options.publicId) != null ? ref.replace(/\//g, ":") : void 0;
    };


    /**
     * Get the public ID, with format if present
     * @function Layer#getFullPublicId
     * @return {String} public ID
     */

    Layer.prototype.getFullPublicId = function() {
      if (this.options.format != null) {
        return this.getPublicId() + "." + this.options.format;
      } else {
        return this.getPublicId();
      }
    };

    Layer.prototype.format = function(value) {
      this.options.format = value;
      return this;
    };


    /**
     * generate the string representation of the layer
     * @function Layer#toString
     */

    Layer.prototype.toString = function() {
      var components;
      components = [];
      if (this.options.publicId == null) {
        throw "Must supply publicId";
      }
      if (!(this.options.resourceType === "image")) {
        components.push(this.options.resourceType);
      }
      if (!(this.options.type === "upload")) {
        components.push(this.options.type);
      }
      components.push(this.getFullPublicId());
      return Util.compact(components).join(":");
    };

    return Layer;

  })();
  FetchLayer = (function(superClass) {
    extend(FetchLayer, superClass);


    /**
     * @constructor FetchLayer
     * @param {Object|string} options - layer parameters or a url
     * @param {string} options.url the url of the image to fetch
     */

    function FetchLayer(options) {
      FetchLayer.__super__.constructor.call(this, options);
      if (Util.isString(options)) {
        this.options.url = options;
      } else if (options != null ? options.url : void 0) {
        this.options.url = options.url;
      }
    }

    FetchLayer.prototype.url = function(url) {
      this.options.url = url;
      return this;
    };


    /**
     * generate the string representation of the layer
     * @function FetchLayer#toString
     * @return {String}
     */

    FetchLayer.prototype.toString = function() {
      return "fetch:" + (cloudinary.Util.base64EncodeURL(this.options.url));
    };

    return FetchLayer;

  })(Layer);
  TextLayer = (function(superClass) {
    extend(TextLayer, superClass);


    /**
     * @constructor TextLayer
     * @param {Object} options - layer parameters
     */

    function TextLayer(options) {
      var keys;
      TextLayer.__super__.constructor.call(this, options);
      keys = ["resourceType", "resourceType", "fontFamily", "fontSize", "fontWeight", "fontStyle", "textDecoration", "textAlign", "stroke", "letterSpacing", "lineSpacing", "text"];
      if (options != null) {
        keys.forEach((function(_this) {
          return function(key) {
            var ref;
            return _this.options[key] = (ref = options[key]) != null ? ref : options[Util.snakeCase(key)];
          };
        })(this));
      }
      this.options.resourceType = "text";
    }

    TextLayer.prototype.resourceType = function(resourceType) {
      throw "Cannot modify resourceType for text layers";
    };

    TextLayer.prototype.type = function(type) {
      throw "Cannot modify type for text layers";
    };

    TextLayer.prototype.format = function(format) {
      throw "Cannot modify format for text layers";
    };

    TextLayer.prototype.fontFamily = function(fontFamily) {
      this.options.fontFamily = fontFamily;
      return this;
    };

    TextLayer.prototype.fontSize = function(fontSize) {
      this.options.fontSize = fontSize;
      return this;
    };

    TextLayer.prototype.fontWeight = function(fontWeight) {
      this.options.fontWeight = fontWeight;
      return this;
    };

    TextLayer.prototype.fontStyle = function(fontStyle) {
      this.options.fontStyle = fontStyle;
      return this;
    };

    TextLayer.prototype.textDecoration = function(textDecoration) {
      this.options.textDecoration = textDecoration;
      return this;
    };

    TextLayer.prototype.textAlign = function(textAlign) {
      this.options.textAlign = textAlign;
      return this;
    };

    TextLayer.prototype.stroke = function(stroke) {
      this.options.stroke = stroke;
      return this;
    };

    TextLayer.prototype.letterSpacing = function(letterSpacing) {
      this.options.letterSpacing = letterSpacing;
      return this;
    };

    TextLayer.prototype.lineSpacing = function(lineSpacing) {
      this.options.lineSpacing = lineSpacing;
      return this;
    };

    TextLayer.prototype.text = function(text) {
      this.options.text = text;
      return this;
    };


    /**
     * generate the string representation of the layer
     * @function TextLayer#toString
     * @return {String}
     */

    TextLayer.prototype.toString = function() {
      var components, hasPublicId, hasStyle, publicId, re, res, start, style, text, textSource;
      style = this.textStyleIdentifier();
      if (this.options.publicId != null) {
        publicId = this.getFullPublicId();
      }
      if (this.options.text != null) {
        hasPublicId = !Util.isEmpty(publicId);
        hasStyle = !Util.isEmpty(style);
        if (hasPublicId && hasStyle || !hasPublicId && !hasStyle) {
          throw "Must supply either style parameters or a public_id when providing text parameter in a text overlay/underlay, but not both!";
        }
        re = /\$\([a-zA-Z]\w*\)/g;
        start = 0;
        textSource = Util.smartEscape(this.options.text, /[,\/]/g);
        text = "";
        while (res = re.exec(textSource)) {
          text += Util.smartEscape(textSource.slice(start, res.index));
          text += res[0];
          start = res.index + res[0].length;
        }
        text += Util.smartEscape(textSource.slice(start));
      }
      components = [this.options.resourceType, style, publicId, text];
      return Util.compact(components).join(":");
    };

    TextLayer.prototype.textStyleIdentifier = function() {
      var components;
      components = [];
      if (this.options.fontWeight !== "normal") {
        components.push(this.options.fontWeight);
      }
      if (this.options.fontStyle !== "normal") {
        components.push(this.options.fontStyle);
      }
      if (this.options.textDecoration !== "none") {
        components.push(this.options.textDecoration);
      }
      components.push(this.options.textAlign);
      if (this.options.stroke !== "none") {
        components.push(this.options.stroke);
      }
      if (!(Util.isEmpty(this.options.letterSpacing) && !Util.isNumberLike(this.options.letterSpacing))) {
        components.push("letter_spacing_" + this.options.letterSpacing);
      }
      if (!(Util.isEmpty(this.options.lineSpacing) && !Util.isNumberLike(this.options.lineSpacing))) {
        components.push("line_spacing_" + this.options.lineSpacing);
      }
      if (!Util.isEmpty(Util.compact(components))) {
        if (Util.isEmpty(this.options.fontFamily)) {
          throw "Must supply fontFamily. " + components;
        }
        if (Util.isEmpty(this.options.fontSize) && !Util.isNumberLike(this.options.fontSize)) {
          throw "Must supply fontSize.";
        }
      }
      components.unshift(this.options.fontFamily, this.options.fontSize);
      components = Util.compact(components).join("_");
      return components;
    };

    return TextLayer;

  })(Layer);
  SubtitlesLayer = (function(superClass) {
    extend(SubtitlesLayer, superClass);


    /**
     * Represent a subtitles layer
     * @constructor SubtitlesLayer
     * @param {Object} options - layer parameters
     */

    function SubtitlesLayer(options) {
      SubtitlesLayer.__super__.constructor.call(this, options);
      this.options.resourceType = "subtitles";
    }

    return SubtitlesLayer;

  })(TextLayer);

  /**
   * Transformation parameters
   * Depends on 'util', 'transformation'
   */
  Param = (function() {

    /**
     * Represents a single parameter
     * @class Param
     * @param {string} name - The name of the parameter in snake_case
     * @param {string} shortName - The name of the serialized form of the parameter.
     *                         If a value is not provided, the parameter will not be serialized.
     * @param {function} [process=cloudinary.Util.identity ] - Manipulate origValue when value is called
     * @ignore
     */
    function Param(name, shortName, process) {
      if (process == null) {
        process = cloudinary.Util.identity;
      }

      /**
       * The name of the parameter in snake_case
       * @member {string} Param#name
       */
      this.name = name;

      /**
       * The name of the serialized form of the parameter
       * @member {string} Param#shortName
       */
      this.shortName = shortName;

      /**
       * Manipulate origValue when value is called
       * @member {function} Param#process
       */
      this.process = process;
    }


    /**
     * Set a (unprocessed) value for this parameter
     * @function Param#set
     * @param {*} origValue - the value of the parameter
     * @return {Param} self for chaining
     */

    Param.prototype.set = function(origValue) {
      this.origValue = origValue;
      return this;
    };


    /**
     * Generate the serialized form of the parameter
     * @function Param#serialize
     * @return {string} the serialized form of the parameter
     */

    Param.prototype.serialize = function() {
      var val, valid;
      val = this.value();
      valid = cloudinary.Util.isArray(val) || cloudinary.Util.isPlainObject(val) || cloudinary.Util.isString(val) ? !cloudinary.Util.isEmpty(val) : val != null;
      if ((this.shortName != null) && valid) {
        return this.shortName + "_" + val;
      } else {
        return '';
      }
    };


    /**
     * Return the processed value of the parameter
     * @function Param#value
     */

    Param.prototype.value = function() {
      return this.process(this.origValue);
    };

    Param.norm_color = function(value) {
      return value != null ? value.replace(/^#/, 'rgb:') : void 0;
    };

    Param.prototype.build_array = function(arg) {
      if (arg == null) {
        arg = [];
      }
      if (cloudinary.Util.isArray(arg)) {
        return arg;
      } else {
        return [arg];
      }
    };


    /**
    * Covert value to video codec string.
    *
    * If the parameter is an object,
    * @param {(string|Object)} param - the video codec as either a String or a Hash
    * @return {string} the video codec string in the format codec:profile:level
    * @example
    * vc_[ :profile : [level]]
    * or
      { codec: 'h264', profile: 'basic', level: '3.1' }
    * @ignore
     */

    Param.process_video_params = function(param) {
      var video;
      switch (param.constructor) {
        case Object:
          video = "";
          if ('codec' in param) {
            video = param['codec'];
            if ('profile' in param) {
              video += ":" + param['profile'];
              if ('level' in param) {
                video += ":" + param['level'];
              }
            }
          }
          return video;
        case String:
          return param;
        default:
          return null;
      }
    };

    return Param;

  })();
  ArrayParam = (function(superClass) {
    extend(ArrayParam, superClass);


    /**
     * A parameter that represents an array
     * @param {string} name - The name of the parameter in snake_case
     * @param {string} shortName - The name of the serialized form of the parameter
     *                         If a value is not provided, the parameter will not be serialized.
     * @param {string} [sep='.'] - The separator to use when joining the array elements together
     * @param {function} [process=cloudinary.Util.identity ] - Manipulate origValue when value is called
     * @class ArrayParam
     * @extends Param
     * @ignore
     */

    function ArrayParam(name, shortName, sep, process) {
      if (sep == null) {
        sep = '.';
      }
      this.sep = sep;
      ArrayParam.__super__.constructor.call(this, name, shortName, process);
    }

    ArrayParam.prototype.serialize = function() {
      var arrayValue, flat, t;
      if (this.shortName != null) {
        arrayValue = this.value();
        if (cloudinary.Util.isEmpty(arrayValue)) {
          return '';
        } else if (cloudinary.Util.isString(arrayValue)) {
          return this.shortName + "_" + arrayValue;
        } else {
          flat = (function() {
            var j, len, results;
            results = [];
            for (j = 0, len = arrayValue.length; j < len; j++) {
              t = arrayValue[j];
              if (cloudinary.Util.isFunction(t.serialize)) {
                results.push(t.serialize());
              } else {
                results.push(t);
              }
            }
            return results;
          })();
          return this.shortName + "_" + (flat.join(this.sep));
        }
      } else {
        return '';
      }
    };

    ArrayParam.prototype.value = function() {
      var j, len, ref, results, v;
      if (cloudinary.Util.isArray(this.origValue)) {
        ref = this.origValue;
        results = [];
        for (j = 0, len = ref.length; j < len; j++) {
          v = ref[j];
          results.push(this.process(v));
        }
        return results;
      } else {
        return this.process(this.origValue);
      }
    };

    ArrayParam.prototype.set = function(origValue) {
      if ((origValue == null) || cloudinary.Util.isArray(origValue)) {
        return ArrayParam.__super__.set.call(this, origValue);
      } else {
        return ArrayParam.__super__.set.call(this, [origValue]);
      }
    };

    return ArrayParam;

  })(Param);
  TransformationParam = (function(superClass) {
    extend(TransformationParam, superClass);


    /**
     * A parameter that represents a transformation
     * @param {string} name - The name of the parameter in snake_case
     * @param {string} [shortName='t'] - The name of the serialized form of the parameter
     * @param {string} [sep='.'] - The separator to use when joining the array elements together
     * @param {function} [process=cloudinary.Util.identity ] - Manipulate origValue when value is called
     * @class TransformationParam
     * @extends Param
     * @ignore
     */

    function TransformationParam(name, shortName, sep, process) {
      if (shortName == null) {
        shortName = "t";
      }
      if (sep == null) {
        sep = '.';
      }
      this.sep = sep;
      TransformationParam.__super__.constructor.call(this, name, shortName, process);
    }

    TransformationParam.prototype.serialize = function() {
      var joined, result, t;
      if (cloudinary.Util.isEmpty(this.value())) {
        return '';
      } else if (cloudinary.Util.allStrings(this.value())) {
        joined = this.value().join(this.sep);
        if (!cloudinary.Util.isEmpty(joined)) {
          return this.shortName + "_" + joined;
        } else {
          return '';
        }
      } else {
        result = (function() {
          var j, len, ref, results;
          ref = this.value();
          results = [];
          for (j = 0, len = ref.length; j < len; j++) {
            t = ref[j];
            if (t != null) {
              if (cloudinary.Util.isString(t) && !cloudinary.Util.isEmpty(t)) {
                results.push(this.shortName + "_" + t);
              } else if (cloudinary.Util.isFunction(t.serialize)) {
                results.push(t.serialize());
              } else if (cloudinary.Util.isPlainObject(t) && !cloudinary.Util.isEmpty(t)) {
                results.push(new Transformation(t).serialize());
              } else {
                results.push(void 0);
              }
            }
          }
          return results;
        }).call(this);
        return cloudinary.Util.compact(result);
      }
    };

    TransformationParam.prototype.set = function(origValue1) {
      this.origValue = origValue1;
      if (cloudinary.Util.isArray(this.origValue)) {
        return TransformationParam.__super__.set.call(this, this.origValue);
      } else {
        return TransformationParam.__super__.set.call(this, [this.origValue]);
      }
    };

    return TransformationParam;

  })(Param);
  RangeParam = (function(superClass) {
    extend(RangeParam, superClass);


    /**
     * A parameter that represents a range
     * @param {string} name - The name of the parameter in snake_case
     * @param {string} shortName - The name of the serialized form of the parameter
     *                         If a value is not provided, the parameter will not be serialized.
     * @param {function} [process=norm_range_value ] - Manipulate origValue when value is called
     * @class RangeParam
     * @extends Param
     * @ignore
     */

    function RangeParam(name, shortName, process) {
      if (process == null) {
        process = this.norm_range_value;
      }
      RangeParam.__super__.constructor.call(this, name, shortName, process);
    }

    RangeParam.norm_range_value = function(value) {
      var modifier, offset;
      offset = String(value).match(new RegExp('^' + offset_any_pattern + '$'));
      if (offset) {
        modifier = offset[5] != null ? 'p' : '';
        value = (offset[1] || offset[4]) + modifier;
      }
      return value;
    };

    return RangeParam;

  })(Param);
  RawParam = (function(superClass) {
    extend(RawParam, superClass);

    function RawParam(name, shortName, process) {
      if (process == null) {
        process = cloudinary.Util.identity;
      }
      RawParam.__super__.constructor.call(this, name, shortName, process);
    }

    RawParam.prototype.serialize = function() {
      return this.value();
    };

    return RawParam;

  })(Param);
  LayerParam = (function(superClass) {
    var LAYER_KEYWORD_PARAMS;

    extend(LayerParam, superClass);

    function LayerParam() {
      return LayerParam.__super__.constructor.apply(this, arguments);
    }

    LayerParam.prototype.value = function() {
      var layerOptions, result;
      layerOptions = this.origValue;
      if (cloudinary.Util.isPlainObject(layerOptions)) {
        layerOptions = Util.withCamelCaseKeys(layerOptions);
        if (layerOptions.resourceType === "text" || (layerOptions.text != null)) {
          result = new cloudinary.TextLayer(layerOptions).toString();
        } else if (layerOptions.resourceType === "subtitles") {
          result = new cloudinary.SubtitlesLayer(layerOptions).toString();
        } else if (layerOptions.resourceType === "fetch" || (layerOptions.url != null)) {
          result = new cloudinary.FetchLayer(layerOptions).toString();
        } else {
          result = new cloudinary.Layer(layerOptions).toString();
        }
      } else if (/^fetch:.+/.test(layerOptions)) {
        result = new FetchLayer(layerOptions.substr(6)).toString();
      } else {
        result = layerOptions;
      }
      return result;
    };

    LAYER_KEYWORD_PARAMS = [["font_weight", "normal"], ["font_style", "normal"], ["text_decoration", "none"], ["text_align", null], ["stroke", "none"], ["letter_spacing", null], ["line_spacing", null]];

    LayerParam.prototype.textStyle = function(layer) {
      return (new cloudinary.TextLayer(layer)).textStyleIdentifier();
    };

    return LayerParam;

  })(Param);
  ExpressionParam = (function(superClass) {
    extend(ExpressionParam, superClass);

    function ExpressionParam() {
      return ExpressionParam.__super__.constructor.apply(this, arguments);
    }

    ExpressionParam.prototype.serialize = function() {
      return Expression.normalize(ExpressionParam.__super__.serialize.call(this));
    };

    return ExpressionParam;

  })(Param);
  parameters = {};
  parameters.Param = Param;
  parameters.ArrayParam = ArrayParam;
  parameters.RangeParam = RangeParam;
  parameters.RawParam = RawParam;
  parameters.TransformationParam = TransformationParam;
  parameters.LayerParam = LayerParam;
  parameters.ExpressionParam = ExpressionParam;
  Expression = (function() {

    /**
     * @internal
     */
    var faceCount;

    Expression.OPERATORS = {
      "=": 'eq',
      "!=": 'ne',
      "<": 'lt',
      ">": 'gt',
      "<=": 'lte',
      ">=": 'gte',
      "&&": 'and',
      "||": 'or',
      "*": "mul",
      "/": "div",
      "+": "add",
      "-": "sub"
    };


    /**
     * @internal
     */

    Expression.PREDEFINED_VARS = {
      "aspect_ratio": "ar",
      "aspectRatio": "ar",
      "current_page": "cp",
      "currentPage": "cp",
      "face_count": "fc",
      "faceCount": "fc",
      "height": "h",
      "initial_aspect_ratio": "iar",
      "initial_height": "ih",
      "initial_width": "iw",
      "initialAspectRatio": "iar",
      "initialHeight": "ih",
      "initialWidth": "iw",
      "page_count": "pc",
      "page_x": "px",
      "page_y": "py",
      "pageCount": "pc",
      "pageX": "px",
      "pageY": "py",
      "tags": "tags",
      "width": "w"
    };


    /**
     * @internal
     */

    Expression.BOUNDRY = "[ _]+";


    /**
     * Represents a transformation expression
     * @param {string} expressionStr - a expression in string format
     * @class Expression
     *
     */

    function Expression(expressionStr) {

      /**
        * @protected
        * @inner Expression-expressions
       */
      this.expressions = [];
      if (expressionStr != null) {
        this.expressions.push(Expression.normalize(expressionStr));
      }
    }


    /**
     * Convenience constructor method
     * @function Expression.new
     */

    Expression["new"] = function(expressionStr) {
      return new this(expressionStr);
    };


    /**
     * Normalize a string expression
     * @function Cloudinary#normalize
     * @param {string} expression a expression, e.g. "w gt 100", "width_gt_100", "width > 100"
     * @return {string} the normalized form of the value expression, e.g. "w_gt_100"
     */

    Expression.normalize = function(expression) {
      var operators, pattern, replaceRE;
      if (expression == null) {
        return expression;
      }
      expression = String(expression);
      operators = "\\|\\||>=|<=|&&|!=|>|=|<|/|-|\\+|\\*";
      pattern = "((" + operators + ")(?=[ _])|" + Object.keys(Expression.PREDEFINED_VARS).join("|") + ")";
      replaceRE = new RegExp(pattern, "g");
      expression = expression.replace(replaceRE, function(match) {
        return Expression.OPERATORS[match] || Expression.PREDEFINED_VARS[match];
      });
      return expression.replace(/[ _]+/g, '_');
    };


    /**
     * Serialize the expression
     * @return {string} the expression as a string
     */

    Expression.prototype.serialize = function() {
      return Expression.normalize(this.expressions.join("_"));
    };

    Expression.prototype.toString = function() {
      return this.serialize();
    };


    /**
     * Get the parent transformation of this expression
     * @return Transformation
     */

    Expression.prototype.getParent = function() {
      return this.parent;
    };


    /**
     * Set the parent transformation of this expression
     * @param {Transformation} the parent transformation
     * @return {Expression} this expression
     */

    Expression.prototype.setParent = function(parent) {
      this.parent = parent;
      return this;
    };


    /**
     * Add a expression
     * @function Expression#predicate
     * @internal
     */

    Expression.prototype.predicate = function(name, operator, value) {
      if (Expression.OPERATORS[operator] != null) {
        operator = Expression.OPERATORS[operator];
      }
      this.expressions.push(name + "_" + operator + "_" + value);
      return this;
    };


    /**
     * @function Expression#and
     */

    Expression.prototype.and = function() {
      this.expressions.push("and");
      return this;
    };


    /**
     * @function Expression#or
     */

    Expression.prototype.or = function() {
      this.expressions.push("or");
      return this;
    };


    /**
     * Conclude expression
     * @function Expression#then
     * @return {Transformation} the transformation this expression is defined for
     */

    Expression.prototype.then = function() {
      return this.getParent()["if"](this.toString());
    };


    /**
     * @function Expression#height
     * @param {string} operator the comparison operator (e.g. "<", "lt")
     * @param {string|number} value the right hand side value
     * @return {Expression} this expression
     */

    Expression.prototype.height = function(operator, value) {
      return this.predicate("h", operator, value);
    };


    /**
     * @function Expression#width
     * @param {string} operator the comparison operator (e.g. "<", "lt")
     * @param {string|number} value the right hand side value
     * @return {Expression} this expression
     */

    Expression.prototype.width = function(operator, value) {
      return this.predicate("w", operator, value);
    };


    /**
     * @function Expression#aspectRatio
     * @param {string} operator the comparison operator (e.g. "<", "lt")
     * @param {string|number} value the right hand side value
     * @return {Expression} this expression
     */

    Expression.prototype.aspectRatio = function(operator, value) {
      return this.predicate("ar", operator, value);
    };


    /**
     * @function Expression#pages
     * @param {string} operator the comparison operator (e.g. "<", "lt")
     * @param {string|number} value the right hand side value
     * @return {Expression} this expression
     */

    Expression.prototype.pageCount = function(operator, value) {
      return this.predicate("pc", operator, value);
    };


    /**
     * @function Expression#faces
     * @param {string} operator the comparison operator (e.g. "<", "lt")
     * @param {string|number} value the right hand side value
     * @return {Expression} this expression
     */

    Expression.prototype.faceCount = function(operator, value) {
      return this.predicate("fc", operator, value);
    };

    Expression.prototype.value = function(value) {
      this.expressions.push(value);
      return this;
    };


    /**
     */

    Expression.variable = function(name, value) {
      return new this(name).value(value);
    };


    /**
      * @returns a new expression with the predefined variable "width"
      * @function Expression.width
     */

    Expression.width = function() {
      return new this("width");
    };


    /**
      * @returns a new expression with the predefined variable "height"
      * @function Expression.height
     */

    Expression.height = function() {
      return new this("height");
    };


    /**
      * @returns a new expression with the predefined variable "initialWidth"
      * @function Expression.initialWidth
     */

    Expression.initialWidth = function() {
      return new this("initialWidth");
    };


    /**
      * @returns a new expression with the predefined variable "initialHeight"
      * @function Expression.initialHeight
     */

    Expression.initialHeight = function() {
      return new this("initialHeight");
    };


    /**
      * @returns a new expression with the predefined variable "aspectRatio"
      * @function Expression.aspectRatio
     */

    Expression.aspectRatio = function() {
      return new this("aspectRatio");
    };


    /**
      * @returns a new expression with the predefined variable "initialAspectRatio"
      * @function Expression.initialAspectRatio
     */

    Expression.initialAspectRatio = function() {
      return new this("initialAspectRatio");
    };


    /**
      * @returns a new expression with the predefined variable "pageCount"
      * @function Expression.pageCount
     */

    Expression.pageCount = function() {
      return new this("pageCount");
    };


    /**
      * @returns a new expression with the predefined variable "faceCount"
      * @function Expression.faceCount
     */

    faceCount = function() {
      return new this("faceCount");
    };


    /**
      * @returns a new expression with the predefined variable "currentPage"
      * @function Expression.currentPage
     */

    Expression.currentPage = function() {
      return new this("currentPage");
    };


    /**
      * @returns a new expression with the predefined variable "tags"
      * @function Expression.tags
     */

    Expression.tags = function() {
      return new this("tags");
    };


    /**
      * @returns a new expression with the predefined variable "pageX"
      * @function Expression.pageX
     */

    Expression.pageX = function() {
      return new this("pageX");
    };


    /**
      * @returns a new expression with the predefined variable "pageY"
      * @function Expression.pageY
     */

    Expression.pageY = function() {
      return new this("pageY");
    };

    return Expression;

  })();
  Condition = (function(superClass) {
    extend(Condition, superClass);


    /**
     * Represents a transformation condition
     * @param {string} conditionStr - a condition in string format
     * @class Condition
     * @example
     * // normally this class is not instantiated directly
     * var tr = cloudinary.Transformation.new()
     *    .if().width( ">", 1000).and().aspectRatio("<", "3:4").then()
     *      .width(1000)
     *      .crop("scale")
     *    .else()
     *      .width(500)
     *      .crop("scale")
     *
     * var tr = cloudinary.Transformation.new()
     *    .if("w > 1000 and aspectRatio < 3:4")
     *      .width(1000)
     *      .crop("scale")
     *    .else()
     *      .width(500)
     *      .crop("scale")
     *
     */

    function Condition(conditionStr) {
      Condition.__super__.constructor.call(this, conditionStr);
    }


    /**
     * @function Condition#height
     * @param {string} operator the comparison operator (e.g. "<", "lt")
     * @param {string|number} value the right hand side value
     * @return {Condition} this condition
     */

    Condition.prototype.height = function(operator, value) {
      return this.predicate("h", operator, value);
    };


    /**
     * @function Condition#width
     * @param {string} operator the comparison operator (e.g. "<", "lt")
     * @param {string|number} value the right hand side value
     * @return {Condition} this condition
     */

    Condition.prototype.width = function(operator, value) {
      return this.predicate("w", operator, value);
    };


    /**
     * @function Condition#aspectRatio
     * @param {string} operator the comparison operator (e.g. "<", "lt")
     * @param {string|number} value the right hand side value
     * @return {Condition} this condition
     */

    Condition.prototype.aspectRatio = function(operator, value) {
      return this.predicate("ar", operator, value);
    };


    /**
     * @function Condition#pages
     * @param {string} operator the comparison operator (e.g. "<", "lt")
     * @param {string|number} value the right hand side value
     * @return {Condition} this condition
     */

    Condition.prototype.pageCount = function(operator, value) {
      return this.predicate("pc", operator, value);
    };


    /**
     * @function Condition#faces
     * @param {string} operator the comparison operator (e.g. "<", "lt")
     * @param {string|number} value the right hand side value
     * @return {Condition} this condition
     */

    Condition.prototype.faceCount = function(operator, value) {
      return this.predicate("fc", operator, value);
    };

    return Condition;

  })(Expression);

  /**
   * Cloudinary configuration class
   * Depends on 'utils'
   */
  Configuration = (function() {

    /**
     * Defaults configuration.
     */
    var DEFAULT_CONFIGURATION_PARAMS, ref;

    DEFAULT_CONFIGURATION_PARAMS = {
      responsive_class: 'cld-responsive',
      responsive_use_breakpoints: true,
      round_dpr: true,
      secure: (typeof window !== "undefined" && window !== null ? (ref = window.location) != null ? ref.protocol : void 0 : void 0) === 'https:'
    };

    Configuration.CONFIG_PARAMS = ["api_key", "api_secret", "callback", "cdn_subdomain", "cloud_name", "cname", "private_cdn", "protocol", "resource_type", "responsive", "responsive_class", "responsive_use_breakpoints", "responsive_width", "round_dpr", "secure", "secure_cdn_subdomain", "secure_distribution", "shorten", "type", "upload_preset", "url_suffix", "use_root_path", "version"];


    /**
     * Cloudinary configuration class
     * @constructor Configuration
     * @param {Object} options - configuration parameters
     */

    function Configuration(options) {
      if (options == null) {
        options = {};
      }
      this.configuration = Util.cloneDeep(options);
      Util.defaults(this.configuration, DEFAULT_CONFIGURATION_PARAMS);
    }


    /**
     * Initialize the configuration.
     * The function first tries to retrieve the configuration form the environment and then from the document.
     * @function Configuration#init
     * @return {Configuration} returns this for chaining
     * @see fromDocument
     * @see fromEnvironment
     */

    Configuration.prototype.init = function() {
      this.fromEnvironment();
      this.fromDocument();
      return this;
    };


    /**
     * Set a new configuration item
     * @function Configuration#set
     * @param {string} name - the name of the item to set
     * @param {*} value - the value to be set
     * @return {Configuration}
     *
     */

    Configuration.prototype.set = function(name, value) {
      this.configuration[name] = value;
      return this;
    };


    /**
     * Get the value of a configuration item
     * @function Configuration#get
     * @param {string} name - the name of the item to set
     * @return {*} the configuration item
     */

    Configuration.prototype.get = function(name) {
      return this.configuration[name];
    };

    Configuration.prototype.merge = function(config) {
      if (config == null) {
        config = {};
      }
      Util.assign(this.configuration, Util.cloneDeep(config));
      return this;
    };


    /**
     * Initialize Cloudinary from HTML meta tags.
     * @function Configuration#fromDocument
     * @return {Configuration}
     * @example <meta name="cloudinary_cloud_name" content="mycloud">
     *
     */

    Configuration.prototype.fromDocument = function() {
      var el, j, len, meta_elements;
      meta_elements = typeof document !== "undefined" && document !== null ? document.querySelectorAll('meta[name^="cloudinary_"]') : void 0;
      if (meta_elements) {
        for (j = 0, len = meta_elements.length; j < len; j++) {
          el = meta_elements[j];
          this.configuration[el.getAttribute('name').replace('cloudinary_', '')] = el.getAttribute('content');
        }
      }
      return this;
    };


    /**
     * Initialize Cloudinary from the `CLOUDINARY_URL` environment variable.
     *
     * This function will only run under Node.js environment.
     * @function Configuration#fromEnvironment
     * @requires Node.js
     */

    Configuration.prototype.fromEnvironment = function() {
      var cloudinary_url, j, k, len, query, ref1, ref2, ref3, uri, uriRegex, v, value;
      cloudinary_url = typeof process !== "undefined" && process !== null ? (ref1 = process.env) != null ? ref1.CLOUDINARY_URL : void 0 : void 0;
      if (cloudinary_url != null) {
        uriRegex = /cloudinary:\/\/(?:(\w+)(?:\:([\w-]+))?@)?([\w\.-]+)(?:\/([^?]*))?(?:\?(.+))?/;
        uri = uriRegex.exec(cloudinary_url);
        if (uri) {
          if (uri[3] != null) {
            this.configuration['cloud_name'] = uri[3];
          }
          if (uri[1] != null) {
            this.configuration['api_key'] = uri[1];
          }
          if (uri[2] != null) {
            this.configuration['api_secret'] = uri[2];
          }
          if (uri[4] != null) {
            this.configuration['private_cdn'] = uri[4] != null;
          }
          if (uri[4] != null) {
            this.configuration['secure_distribution'] = uri[4];
          }
          query = uri[5];
          if (query != null) {
            ref2 = query.split('&');
            for (j = 0, len = ref2.length; j < len; j++) {
              value = ref2[j];
              ref3 = value.split('='), k = ref3[0], v = ref3[1];
              if (v == null) {
                v = true;
              }
              this.configuration[k] = v;
            }
          }
        }
      }
      return this;
    };


    /**
     * Create or modify the Cloudinary client configuration
     *
     * Warning: `config()` returns the actual internal configuration object. modifying it will change the configuration.
     *
     * This is a backward compatibility method. For new code, use get(), merge() etc.
     * @function Configuration#config
     * @param {hash|string|boolean} new_config
     * @param {string} new_value
     * @returns {*} configuration, or value
     *
     * @see {@link fromEnvironment} for initialization using environment variables
     * @see {@link fromDocument} for initialization using HTML meta tags
     */

    Configuration.prototype.config = function(new_config, new_value) {
      switch (false) {
        case new_value === void 0:
          this.set(new_config, new_value);
          return this.configuration;
        case !Util.isString(new_config):
          return this.get(new_config);
        case !Util.isPlainObject(new_config):
          this.merge(new_config);
          return this.configuration;
        default:
          return this.configuration;
      }
    };


    /**
     * Returns a copy of the configuration parameters
     * @function Configuration#toOptions
     * @returns {Object} a key:value collection of the configuration parameters
     */

    Configuration.prototype.toOptions = function() {
      return Util.cloneDeep(this.configuration);
    };

    return Configuration;

  })();

  /**
   * TransformationBase
   * Depends on 'configuration', 'parameters','util'
   * @internal
   */
  TransformationBase = (function() {
    var VAR_NAME_RE, lastArgCallback, processVar;

    VAR_NAME_RE = /^\$[a-zA-Z0-9]+$/;

    TransformationBase.prototype.trans_separator = '/';

    TransformationBase.prototype.param_separator = ',';

    lastArgCallback = function(args) {
      var callback;
      callback = args != null ? args[args.length - 1] : void 0;
      if (Util.isFunction(callback)) {
        return callback;
      } else {
        return void 0;
      }
    };


    /**
     * The base class for transformations.
     * Members of this class are documented as belonging to the {@link Transformation} class for convenience.
     * @class TransformationBase
     */

    function TransformationBase(options) {
      var parent, trans;
      if (options == null) {
        options = {};
      }

      /** @private */
      parent = void 0;

      /** @private */
      trans = {};

      /**
       * Return an options object that can be used to create an identical Transformation
       * @function Transformation#toOptions
       * @return {Object} Returns a plain object representing this transformation
       */
      this.toOptions || (this.toOptions = function(withChain) {
        var key, list, opt, ref, ref1, tr, value;
        if (withChain == null) {
          withChain = true;
        }
        opt = {};
        for (key in trans) {
          value = trans[key];
          opt[key] = value.origValue;
        }
        ref = this.otherOptions;
        for (key in ref) {
          value = ref[key];
          if (value !== void 0) {
            opt[key] = value;
          }
        }
        if (withChain && !Util.isEmpty(this.chained)) {
          list = (function() {
            var j, len, ref1, results;
            ref1 = this.chained;
            results = [];
            for (j = 0, len = ref1.length; j < len; j++) {
              tr = ref1[j];
              results.push(tr.toOptions());
            }
            return results;
          }).call(this);
          list.push(opt);
          opt = {};
          ref1 = this.otherOptions;
          for (key in ref1) {
            value = ref1[key];
            if (value !== void 0) {
              opt[key] = value;
            }
          }
          opt.transformation = list;
        }
        return opt;
      });

      /**
       * Set a parent for this object for chaining purposes.
       *
       * @function Transformation#setParent
       * @param {Object} object - the parent to be assigned to
       * @returns {Transformation} Returns this instance for chaining purposes.
       */
      this.setParent || (this.setParent = function(object) {
        parent = object;
        if (object != null) {
          this.fromOptions(typeof object.toOptions === "function" ? object.toOptions() : void 0);
        }
        return this;
      });

      /**
       * Returns the parent of this object in the chain
       * @function Transformation#getParent
       * @protected
       * @return {Object} Returns the parent of this object if there is any
       */
      this.getParent || (this.getParent = function() {
        return parent;
      });

      /** @protected */
      this.param || (this.param = function(value, name, abbr, defaultValue, process) {
        if (process == null) {
          if (Util.isFunction(defaultValue)) {
            process = defaultValue;
          } else {
            process = Util.identity;
          }
        }
        trans[name] = new Param(name, abbr, process).set(value);
        return this;
      });

      /** @protected */
      this.rawParam || (this.rawParam = function(value, name, abbr, defaultValue, process) {
        if (process == null) {
          process = Util.identity;
        }
        process = lastArgCallback(arguments);
        trans[name] = new RawParam(name, abbr, process).set(value);
        return this;
      });

      /** @protected */
      this.rangeParam || (this.rangeParam = function(value, name, abbr, defaultValue, process) {
        if (process == null) {
          process = Util.identity;
        }
        process = lastArgCallback(arguments);
        trans[name] = new RangeParam(name, abbr, process).set(value);
        return this;
      });

      /** @protected */
      this.arrayParam || (this.arrayParam = function(value, name, abbr, sep, defaultValue, process) {
        if (sep == null) {
          sep = ":";
        }
        if (defaultValue == null) {
          defaultValue = [];
        }
        if (process == null) {
          process = Util.identity;
        }
        process = lastArgCallback(arguments);
        trans[name] = new ArrayParam(name, abbr, sep, process).set(value);
        return this;
      });

      /** @protected */
      this.transformationParam || (this.transformationParam = function(value, name, abbr, sep, defaultValue, process) {
        if (sep == null) {
          sep = ".";
        }
        if (process == null) {
          process = Util.identity;
        }
        process = lastArgCallback(arguments);
        trans[name] = new TransformationParam(name, abbr, sep, process).set(value);
        return this;
      });
      this.layerParam || (this.layerParam = function(value, name, abbr) {
        trans[name] = new LayerParam(name, abbr).set(value);
        return this;
      });

      /**
       * Get the value associated with the given name.
       * @function Transformation#getValue
       * @param {string} name - the name of the parameter
       * @return {*} the processed value associated with the given name
       * @description Use {@link get}.origValue for the value originally provided for the parameter
       */
      this.getValue || (this.getValue = function(name) {
        var ref, ref1;
        return (ref = (ref1 = trans[name]) != null ? ref1.value() : void 0) != null ? ref : this.otherOptions[name];
      });

      /**
       * Get the parameter object for the given parameter name
       * @function Transformation#get
       * @param {string} name the name of the transformation parameter
       * @returns {Param} the param object for the given name, or undefined
       */
      this.get || (this.get = function(name) {
        return trans[name];
      });

      /**
       * Remove a transformation option from the transformation.
       * @function Transformation#remove
       * @param {string} name - the name of the option to remove
       * @return {*} Returns the option that was removed or null if no option by that name was found. The type of the
       *              returned value depends on the value.
       */
      this.remove || (this.remove = function(name) {
        var temp;
        switch (false) {
          case trans[name] == null:
            temp = trans[name];
            delete trans[name];
            return temp.origValue;
          case this.otherOptions[name] == null:
            temp = this.otherOptions[name];
            delete this.otherOptions[name];
            return temp;
          default:
            return null;
        }
      });

      /**
       * Return an array of all the keys (option names) in the transformation.
       * @return {Array<string>} the keys in snakeCase format
       */
      this.keys || (this.keys = function() {
        var key;
        return ((function() {
          var results;
          results = [];
          for (key in trans) {
            if (key != null) {
              results.push(key.match(VAR_NAME_RE) ? key : Util.snakeCase(key));
            }
          }
          return results;
        })()).sort();
      });

      /**
       * Returns a plain object representation of the transformation. Values are processed.
       * @function Transformation#toPlainObject
       * @return {Object} the transformation options as plain object
       */
      this.toPlainObject || (this.toPlainObject = function() {
        var hash, key, list, tr;
        hash = {};
        for (key in trans) {
          hash[key] = trans[key].value();
          if (Util.isPlainObject(hash[key])) {
            hash[key] = Util.cloneDeep(hash[key]);
          }
        }
        if (!Util.isEmpty(this.chained)) {
          list = (function() {
            var j, len, ref, results;
            ref = this.chained;
            results = [];
            for (j = 0, len = ref.length; j < len; j++) {
              tr = ref[j];
              results.push(tr.toPlainObject());
            }
            return results;
          }).call(this);
          list.push(hash);
          hash = {
            transformation: list
          };
        }
        return hash;
      });

      /**
       * Complete the current transformation and chain to a new one.
       * In the URL, transformations are chained together by slashes.
       * @function Transformation#chain
       * @return {Transformation} Returns this transformation for chaining
       * @example
       * var tr = cloudinary.Transformation.new();
       * tr.width(10).crop('fit').chain().angle(15).serialize()
       * // produces "c_fit,w_10/a_15"
       */
      this.chain || (this.chain = function() {
        var names, tr;
        names = Object.getOwnPropertyNames(trans);
        if (names.length !== 0) {
          tr = new this.constructor(this.toOptions(false));
          this.resetTransformations();
          this.chained.push(tr);
        }
        return this;
      });
      this.resetTransformations || (this.resetTransformations = function() {
        trans = {};
        return this;
      });
      this.otherOptions || (this.otherOptions = {});
      this.chained = [];
      if (!Util.isEmpty(options)) {
        this.fromOptions(options);
      }
    }


    /**
     * Merge the provided options with own's options
     * @param {Object} [options={}] key-value list of options
     * @returns {Transformation} Returns this instance for chaining
     */

    TransformationBase.prototype.fromOptions = function(options) {
      var key, opt;
      if (options instanceof TransformationBase) {
        this.fromTransformation(options);
      } else {
        options || (options = {});
        if (Util.isString(options) || Util.isArray(options)) {
          options = {
            transformation: options
          };
        }
        options = Util.cloneDeep(options, function(value) {
          if (value instanceof TransformationBase) {
            return new value.constructor(value.toOptions());
          }
        });
        if (options["if"]) {
          this.set("if", options["if"]);
          delete options["if"];
        }
        for (key in options) {
          opt = options[key];
          if (key.match(VAR_NAME_RE)) {
            if (key !== '$attr') {
              this.set('variable', key, opt);
            }
          } else {
            this.set(key, opt);
          }
        }
      }
      return this;
    };

    TransformationBase.prototype.fromTransformation = function(other) {
      var j, key, len, ref;
      if (other instanceof TransformationBase) {
        ref = other.keys();
        for (j = 0, len = ref.length; j < len; j++) {
          key = ref[j];
          this.set(key, other.get(key).origValue);
        }
      }
      return this;
    };


    /**
     * Set a parameter.
     * The parameter name `key` is converted to
     * @param {string} key - the name of the parameter
     * @param {*} value - the value of the parameter
     * @returns {Transformation} Returns this instance for chaining
     */

    TransformationBase.prototype.set = function() {
      var camelKey, key, values;
      key = arguments[0], values = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      camelKey = Util.camelCase(key);
      if (Util.contains(Transformation.methods, camelKey)) {
        this[camelKey].apply(this, values);
      } else {
        this.otherOptions[key] = values[0];
      }
      return this;
    };

    TransformationBase.prototype.hasLayer = function() {
      return this.getValue("overlay") || this.getValue("underlay");
    };


    /**
     * Generate a string representation of the transformation.
     * @function Transformation#serialize
     * @return {string} Returns the transformation as a string
     */

    TransformationBase.prototype.serialize = function() {
      var ifParam, j, len, paramList, ref, ref1, ref2, ref3, ref4, resultArray, t, tr, transformationList, transformationString, transformations, value, variables, vars;
      resultArray = (function() {
        var j, len, ref, results;
        ref = this.chained;
        results = [];
        for (j = 0, len = ref.length; j < len; j++) {
          tr = ref[j];
          results.push(tr.serialize());
        }
        return results;
      }).call(this);
      paramList = this.keys();
      transformations = (ref = this.get("transformation")) != null ? ref.serialize() : void 0;
      ifParam = (ref1 = this.get("if")) != null ? ref1.serialize() : void 0;
      variables = processVar((ref2 = this.get("variables")) != null ? ref2.value() : void 0);
      paramList = Util.difference(paramList, ["transformation", "if", "variables"]);
      vars = [];
      transformationList = [];
      for (j = 0, len = paramList.length; j < len; j++) {
        t = paramList[j];
        if (t.match(VAR_NAME_RE)) {
          vars.push(t + "_" + Expression.normalize((ref3 = this.get(t)) != null ? ref3.value() : void 0));
        } else {
          transformationList.push((ref4 = this.get(t)) != null ? ref4.serialize() : void 0);
        }
      }
      switch (false) {
        case !Util.isString(transformations):
          transformationList.push(transformations);
          break;
        case !Util.isArray(transformations):
          resultArray = resultArray.concat(transformations);
      }
      transformationList = (function() {
        var l, len1, results;
        results = [];
        for (l = 0, len1 = transformationList.length; l < len1; l++) {
          value = transformationList[l];
          if (Util.isArray(value) && !Util.isEmpty(value) || !Util.isArray(value) && value) {
            results.push(value);
          }
        }
        return results;
      })();
      transformationList = vars.sort().concat(variables).concat(transformationList.sort());
      if (ifParam === "if_end") {
        transformationList.push(ifParam);
      } else if (!Util.isEmpty(ifParam)) {
        transformationList.unshift(ifParam);
      }
      transformationString = Util.compact(transformationList).join(this.param_separator);
      if (!Util.isEmpty(transformationString)) {
        resultArray.push(transformationString);
      }
      return Util.compact(resultArray).join(this.trans_separator);
    };


    /**
     * Provide a list of all the valid transformation option names
     * @function Transformation#listNames
     * @private
     * @return {Array<string>} a array of all the valid option names
     */

    TransformationBase.prototype.listNames = function() {
      return Transformation.methods;
    };


    /**
     * Returns attributes for an HTML tag.
     * @function Cloudinary.toHtmlAttributes
     * @return PlainObject
     */

    TransformationBase.prototype.toHtmlAttributes = function() {
      var attrName, height, j, key, len, options, ref, ref1, ref2, ref3, value;
      options = {};
      ref = this.otherOptions;
      for (key in ref) {
        value = ref[key];
        if (!(!Util.contains(Transformation.PARAM_NAMES, Util.snakeCase(key)))) {
          continue;
        }
        attrName = /^html_/.test(key) ? key.slice(5) : key;
        options[attrName] = value;
      }
      ref1 = this.keys();
      for (j = 0, len = ref1.length; j < len; j++) {
        key = ref1[j];
        if (/^html_/.test(key)) {
          options[Util.camelCase(key.slice(5))] = this.getValue(key);
        }
      }
      if (!(this.hasLayer() || this.getValue("angle") || Util.contains(["fit", "limit", "lfill"], this.getValue("crop")))) {
        width = (ref2 = this.get("width")) != null ? ref2.origValue : void 0;
        height = (ref3 = this.get("height")) != null ? ref3.origValue : void 0;
        if (parseFloat(width) >= 1.0) {
          if (options['width'] == null) {
            options['width'] = width;
          }
        }
        if (parseFloat(height) >= 1.0) {
          if (options['height'] == null) {
            options['height'] = height;
          }
        }
      }
      return options;
    };

    TransformationBase.prototype.isValidParamName = function(name) {
      return Transformation.methods.indexOf(Util.camelCase(name)) >= 0;
    };


    /**
     * Delegate to the parent (up the call chain) to produce HTML
     * @function Transformation#toHtml
     * @return {string} HTML representation of the parent if possible.
     * @example
     * tag = cloudinary.ImageTag.new("sample", {cloud_name: "demo"})
     * // ImageTag {name: "img", publicId: "sample"}
     * tag.toHtml()
     * // <img src="http://res.cloudinary.com/demo/image/upload/sample">
     * tag.transformation().crop("fit").width(300).toHtml()
     * // <img src="http://res.cloudinary.com/demo/image/upload/c_fit,w_300/sample">
     */

    TransformationBase.prototype.toHtml = function() {
      var ref;
      return (ref = this.getParent()) != null ? typeof ref.toHtml === "function" ? ref.toHtml() : void 0 : void 0;
    };

    TransformationBase.prototype.toString = function() {
      return this.serialize();
    };

    processVar = function(varArray) {
      var j, len, name, ref, results, v;
      if (Util.isArray(varArray)) {
        results = [];
        for (j = 0, len = varArray.length; j < len; j++) {
          ref = varArray[j], name = ref[0], v = ref[1];
          results.push(name + "_" + (Expression.normalize(v)));
        }
        return results;
      } else {
        return varArray;
      }

      /**
       * Transformation Class methods.
       * This is a list of the parameters defined in Transformation.
       * Values are camelCased.
       * @const Transformation.methods
       * @private
       * @ignore
       * @type {Array<string>}
       */

      /**
       * Parameters that are filtered out before passing the options to an HTML tag.
       *
       * The list of parameters is a combination of `Transformation::methods` and `Configuration::CONFIG_PARAMS`
       * @const {Array<string>} Transformation.PARAM_NAMES
       * @private
       * @ignore
       * @see toHtmlAttributes
       */
    };

    return TransformationBase;

  })();
  Transformation = (function(superClass) {
    extend(Transformation, superClass);


    /**
     *  Represents a single transformation.
     *  @class Transformation
     *  @example
     *  t = new cloudinary.Transformation();
     * t.angle(20).crop("scale").width("auto");
     *
     * // or
     *
     * t = new cloudinary.Transformation( {angle: 20, crop: "scale", width: "auto"});
     */

    function Transformation(options) {
      if (options == null) {
        options = {};
      }
      Transformation.__super__.constructor.call(this, options);
      this;
    }


    /**
     * Convenience constructor
     * @param {Object} options
     * @return {Transformation}
     * @example cl = cloudinary.Transformation.new( {angle: 20, crop: "scale", width: "auto"})
     */

    Transformation["new"] = function(args) {
      return new Transformation(args);
    };


    /*
      Transformation Parameters
     */

    Transformation.prototype.angle = function(value) {
      return this.arrayParam(value, "angle", "a", ".", Expression.normalize);
    };

    Transformation.prototype.audioCodec = function(value) {
      return this.param(value, "audio_codec", "ac");
    };

    Transformation.prototype.audioFrequency = function(value) {
      return this.param(value, "audio_frequency", "af");
    };

    Transformation.prototype.aspectRatio = function(value) {
      return this.param(value, "aspect_ratio", "ar", Expression.normalize);
    };

    Transformation.prototype.background = function(value) {
      return this.param(value, "background", "b", Param.norm_color);
    };

    Transformation.prototype.bitRate = function(value) {
      return this.param(value, "bit_rate", "br");
    };

    Transformation.prototype.border = function(value) {
      return this.param(value, "border", "bo", function(border) {
        if (Util.isPlainObject(border)) {
          border = Util.assign({}, {
            color: "black",
            width: 2
          }, border);
          return border.width + "px_solid_" + (Param.norm_color(border.color));
        } else {
          return border;
        }
      });
    };

    Transformation.prototype.color = function(value) {
      return this.param(value, "color", "co", Param.norm_color);
    };

    Transformation.prototype.colorSpace = function(value) {
      return this.param(value, "color_space", "cs");
    };

    Transformation.prototype.crop = function(value) {
      return this.param(value, "crop", "c");
    };

    Transformation.prototype.defaultImage = function(value) {
      return this.param(value, "default_image", "d");
    };

    Transformation.prototype.delay = function(value) {
      return this.param(value, "delay", "dl");
    };

    Transformation.prototype.density = function(value) {
      return this.param(value, "density", "dn");
    };

    Transformation.prototype.duration = function(value) {
      return this.rangeParam(value, "duration", "du");
    };

    Transformation.prototype.dpr = function(value) {
      return this.param(value, "dpr", "dpr", (function(_this) {
        return function(dpr) {
          dpr = dpr.toString();
          if (dpr != null ? dpr.match(/^\d+$/) : void 0) {
            return dpr + ".0";
          } else {
            return Expression.normalize(dpr);
          }
        };
      })(this));
    };

    Transformation.prototype.effect = function(value) {
      return this.arrayParam(value, "effect", "e", ":", Expression.normalize);
    };

    Transformation.prototype["else"] = function() {
      return this["if"]('else');
    };

    Transformation.prototype.endIf = function() {
      return this["if"]('end');
    };

    Transformation.prototype.endOffset = function(value) {
      return this.rangeParam(value, "end_offset", "eo");
    };

    Transformation.prototype.fallbackContent = function(value) {
      return this.param(value, "fallback_content");
    };

    Transformation.prototype.fetchFormat = function(value) {
      return this.param(value, "fetch_format", "f");
    };

    Transformation.prototype.format = function(value) {
      return this.param(value, "format");
    };

    Transformation.prototype.flags = function(value) {
      return this.arrayParam(value, "flags", "fl", ".");
    };

    Transformation.prototype.gravity = function(value) {
      return this.param(value, "gravity", "g");
    };

    Transformation.prototype.height = function(value) {
      return this.param(value, "height", "h", (function(_this) {
        return function() {
          if (_this.getValue("crop") || _this.getValue("overlay") || _this.getValue("underlay")) {
            return Expression.normalize(value);
          } else {
            return null;
          }
        };
      })(this));
    };

    Transformation.prototype.htmlHeight = function(value) {
      return this.param(value, "html_height");
    };

    Transformation.prototype.htmlWidth = function(value) {
      return this.param(value, "html_width");
    };

    Transformation.prototype["if"] = function(value) {
      var i, ifVal, j, ref, trIf, trRest;
      if (value == null) {
        value = "";
      }
      switch (value) {
        case "else":
          this.chain();
          return this.param(value, "if", "if");
        case "end":
          this.chain();
          for (i = j = ref = this.chained.length - 1; j >= 0; i = j += -1) {
            ifVal = this.chained[i].getValue("if");
            if (ifVal === "end") {
              break;
            } else if (ifVal != null) {
              trIf = Transformation["new"]()["if"](ifVal);
              this.chained[i].remove("if");
              trRest = this.chained[i];
              this.chained[i] = Transformation["new"]().transformation([trIf, trRest]);
              if (ifVal !== "else") {
                break;
              }
            }
          }
          return this.param(value, "if", "if");
        case "":
          return Condition["new"]().setParent(this);
        default:
          return this.param(value, "if", "if", function(value) {
            return Condition["new"](value).toString();
          });
      }
    };

    Transformation.prototype.keyframeInterval = function(value) {
      return this.param(value, "keyframe_interval", "ki");
    };

    Transformation.prototype.offset = function(value) {
      var end_o, ref, start_o;
      ref = Util.isFunction(value != null ? value.split : void 0) ? value.split('..') : Util.isArray(value) ? value : [null, null], start_o = ref[0], end_o = ref[1];
      if (start_o != null) {
        this.startOffset(start_o);
      }
      if (end_o != null) {
        return this.endOffset(end_o);
      }
    };

    Transformation.prototype.opacity = function(value) {
      return this.param(value, "opacity", "o", Expression.normalize);
    };

    Transformation.prototype.overlay = function(value) {
      return this.layerParam(value, "overlay", "l");
    };

    Transformation.prototype.page = function(value) {
      return this.param(value, "page", "pg");
    };

    Transformation.prototype.poster = function(value) {
      return this.param(value, "poster");
    };

    Transformation.prototype.prefix = function(value) {
      return this.param(value, "prefix", "p");
    };

    Transformation.prototype.quality = function(value) {
      return this.param(value, "quality", "q", Expression.normalize);
    };

    Transformation.prototype.radius = function(value) {
      return this.param(value, "radius", "r", Expression.normalize);
    };

    Transformation.prototype.rawTransformation = function(value) {
      return this.rawParam(value, "raw_transformation");
    };

    Transformation.prototype.size = function(value) {
      var height, ref;
      if (Util.isFunction(value != null ? value.split : void 0)) {
        ref = value.split('x'), width = ref[0], height = ref[1];
        this.width(width);
        return this.height(height);
      }
    };

    Transformation.prototype.sourceTypes = function(value) {
      return this.param(value, "source_types");
    };

    Transformation.prototype.sourceTransformation = function(value) {
      return this.param(value, "source_transformation");
    };

    Transformation.prototype.startOffset = function(value) {
      return this.rangeParam(value, "start_offset", "so");
    };

    Transformation.prototype.streamingProfile = function(value) {
      return this.param(value, "streaming_profile", "sp");
    };

    Transformation.prototype.transformation = function(value) {
      return this.transformationParam(value, "transformation", "t");
    };

    Transformation.prototype.underlay = function(value) {
      return this.layerParam(value, "underlay", "u");
    };

    Transformation.prototype.variable = function(name, value) {
      return this.param(value, name, name);
    };

    Transformation.prototype.variables = function(values) {
      return this.arrayParam(values, "variables");
    };

    Transformation.prototype.videoCodec = function(value) {
      return this.param(value, "video_codec", "vc", Param.process_video_params);
    };

    Transformation.prototype.videoSampling = function(value) {
      return this.param(value, "video_sampling", "vs");
    };

    Transformation.prototype.width = function(value) {
      return this.param(value, "width", "w", (function(_this) {
        return function() {
          if (_this.getValue("crop") || _this.getValue("overlay") || _this.getValue("underlay")) {
            return Expression.normalize(value);
          } else {
            return null;
          }
        };
      })(this));
    };

    Transformation.prototype.x = function(value) {
      return this.param(value, "x", "x", Expression.normalize);
    };

    Transformation.prototype.y = function(value) {
      return this.param(value, "y", "y", Expression.normalize);
    };

    Transformation.prototype.zoom = function(value) {
      return this.param(value, "zoom", "z", Expression.normalize);
    };

    return Transformation;

  })(TransformationBase);

  /**
   * Transformation Class methods.
   * This is a list of the parameters defined in Transformation.
   * Values are camelCased.
   */
  Transformation.methods || (Transformation.methods = Util.difference(Util.functions(Transformation.prototype), Util.functions(TransformationBase.prototype)));

  /**
   * Parameters that are filtered out before passing the options to an HTML tag.
   *
   * The list of parameters is a combination of `Transformation::methods` and `Configuration::CONFIG_PARAMS`
   */
  Transformation.PARAM_NAMES || (Transformation.PARAM_NAMES = ((function() {
    var j, len, ref, results;
    ref = Transformation.methods;
    results = [];
    for (j = 0, len = ref.length; j < len; j++) {
      m = ref[j];
      results.push(Util.snakeCase(m));
    }
    return results;
  })()).concat(Configuration.CONFIG_PARAMS));

  /**
   * Generic HTML tag
   * Depends on 'transformation', 'util'
   */
  HtmlTag = (function() {

    /**
     * Represents an HTML (DOM) tag
     * @constructor HtmlTag
     * @param {string} name - the name of the tag
     * @param {string} [publicId]
     * @param {Object} options
     * @example tag = new HtmlTag( 'div', { 'width': 10})
     */
    var toAttribute;

    function HtmlTag(name, publicId, options) {
      var transformation;
      this.name = name;
      this.publicId = publicId;
      if (options == null) {
        if (Util.isPlainObject(publicId)) {
          options = publicId;
          this.publicId = void 0;
        } else {
          options = {};
        }
      }
      transformation = new Transformation(options);
      transformation.setParent(this);
      this.transformation = function() {
        return transformation;
      };
    }


    /**
     * Convenience constructor
     * Creates a new instance of an HTML (DOM) tag
     * @function HtmlTag.new
     * @param {string} name - the name of the tag
     * @param {string} [publicId]
     * @param {Object} options
     * @return {HtmlTag}
     * @example tag = HtmlTag.new( 'div', { 'width': 10})
     */

    HtmlTag["new"] = function(name, publicId, options) {
      return new this(name, publicId, options);
    };


    /**
     * Represent the given key and value as an HTML attribute.
     * @function HtmlTag#toAttribute
     * @protected
     * @param {string} key - attribute name
     * @param {*|boolean} value - the value of the attribute. If the value is boolean `true`, return the key only.
     * @returns {string} the attribute  
     *
     */

    toAttribute = function(key, value) {
      if (!value) {
        return void 0;
      } else if (value === true) {
        return key;
      } else {
        return key + "=\"" + value + "\"";
      }
    };


    /**
     * combine key and value from the `attr` to generate an HTML tag attributes string.
     * `Transformation::toHtmlTagOptions` is used to filter out transformation and configuration keys.
     * @protected
     * @param {Object} attrs
     * @return {string} the attributes in the format `'key1="value1" key2="value2"'`
     * @ignore
     */

    HtmlTag.prototype.htmlAttrs = function(attrs) {
      var key, pairs, value;
      return pairs = ((function() {
        var results;
        results = [];
        for (key in attrs) {
          value = attrs[key];
          if (value) {
            results.push(toAttribute(key, value));
          }
        }
        return results;
      })()).sort().join(' ');
    };


    /**
     * Get all options related to this tag.
     * @function HtmlTag#getOptions
     * @returns {Object} the options
     *
     */

    HtmlTag.prototype.getOptions = function() {
      return this.transformation().toOptions();
    };


    /**
     * Get the value of option `name`
     * @function HtmlTag#getOption
     * @param {string} name - the name of the option
     * @returns {*} Returns the value of the option
     *
     */

    HtmlTag.prototype.getOption = function(name) {
      return this.transformation().getValue(name);
    };


    /**
     * Get the attributes of the tag.
     * @function HtmlTag#attributes
     * @returns {Object} attributes
     */

    HtmlTag.prototype.attributes = function() {
      return this.transformation().toHtmlAttributes();
    };


    /**
     * Set a tag attribute named `name` to `value`
     * @function HtmlTag#setAttr
     * @param {string} name - the name of the attribute
     * @param {string} value - the value of the attribute
     */

    HtmlTag.prototype.setAttr = function(name, value) {
      this.transformation().set("html_" + name, value);
      return this;
    };


    /**
     * Get the value of the tag attribute `name`
     * @function HtmlTag#getAttr
     * @param {string} name - the name of the attribute
     * @returns {*}
     */

    HtmlTag.prototype.getAttr = function(name) {
      return this.attributes()["html_" + name] || this.attributes()[name];
    };


    /**
     * Remove the tag attributed named `name`
     * @function HtmlTag#removeAttr
     * @param {string} name - the name of the attribute
     * @returns {*}
     */

    HtmlTag.prototype.removeAttr = function(name) {
      var ref;
      return (ref = this.transformation().remove("html_" + name)) != null ? ref : this.transformation().remove(name);
    };


    /**
     * @function HtmlTag#content
     * @protected
     * @ignore
     */

    HtmlTag.prototype.content = function() {
      return "";
    };


    /**
     * @function HtmlTag#openTag
     * @protected
     * @ignore
     */

    HtmlTag.prototype.openTag = function() {
      return "<" + this.name + " " + (this.htmlAttrs(this.attributes())) + ">";
    };


    /**
     * @function HtmlTag#closeTag
     * @protected
     * @ignore
     */

    HtmlTag.prototype.closeTag = function() {
      return "</" + this.name + ">";
    };


    /**
     * Generates an HTML representation of the tag.
     * @function HtmlTag#toHtml
     * @returns {string} Returns HTML in string format
     */

    HtmlTag.prototype.toHtml = function() {
      return this.openTag() + this.content() + this.closeTag();
    };


    /**
     * Creates a DOM object representing the tag.
     * @function HtmlTag#toDOM
     * @returns {Element}
     */

    HtmlTag.prototype.toDOM = function() {
      var element, name, ref, value;
      if (!Util.isFunction(typeof document !== "undefined" && document !== null ? document.createElement : void 0)) {
        throw "Can't create DOM if document is not present!";
      }
      element = document.createElement(this.name);
      ref = this.attributes();
      for (name in ref) {
        value = ref[name];
        element[name] = value;
      }
      return element;
    };

    HtmlTag.isResponsive = function(tag, responsiveClass) {
      var dataSrc;
      dataSrc = Util.getData(tag, 'src-cache') || Util.getData(tag, 'src');
      return Util.hasClass(tag, responsiveClass) && /\bw_auto\b/.exec(dataSrc);
    };

    return HtmlTag;

  })();

  /**
   * Image Tag
   * Depends on 'tags/htmltag', 'cloudinary'
   */
  ImageTag = (function(superClass) {
    extend(ImageTag, superClass);


    /**
     * Creates an HTML (DOM) Image tag using Cloudinary as the source.
     * @constructor ImageTag
     * @extends HtmlTag
     * @param {string} [publicId]
     * @param {Object} [options]
     */

    function ImageTag(publicId, options) {
      if (options == null) {
        options = {};
      }
      ImageTag.__super__.constructor.call(this, "img", publicId, options);
    }


    /** @override */

    ImageTag.prototype.closeTag = function() {
      return "";
    };


    /** @override */

    ImageTag.prototype.attributes = function() {
      var attr, options, srcAttribute;
      attr = ImageTag.__super__.attributes.call(this) || [];
      options = this.getOptions();
      srcAttribute = options.responsive && !options.client_hints ? 'data-src' : 'src';
      if (attr[srcAttribute] == null) {
        attr[srcAttribute] = new Cloudinary(this.getOptions()).url(this.publicId);
      }
      return attr;
    };

    return ImageTag;

  })(HtmlTag);

  /**
   * Video Tag
   * Depends on 'tags/htmltag', 'util', 'cloudinary'
   */
  VideoTag = (function(superClass) {
    var DEFAULT_POSTER_OPTIONS, DEFAULT_VIDEO_SOURCE_TYPES, VIDEO_TAG_PARAMS;

    extend(VideoTag, superClass);

    VIDEO_TAG_PARAMS = ['source_types', 'source_transformation', 'fallback_content', 'poster'];

    DEFAULT_VIDEO_SOURCE_TYPES = ['webm', 'mp4', 'ogv'];

    DEFAULT_POSTER_OPTIONS = {
      format: 'jpg',
      resource_type: 'video'
    };


    /**
     * Creates an HTML (DOM) Video tag using Cloudinary as the source.
     * @constructor VideoTag
     * @extends HtmlTag
     * @param {string} [publicId]
     * @param {Object} [options]
     */

    function VideoTag(publicId, options) {
      if (options == null) {
        options = {};
      }
      options = Util.defaults({}, options, Cloudinary.DEFAULT_VIDEO_PARAMS);
      VideoTag.__super__.constructor.call(this, "video", publicId.replace(/\.(mp4|ogv|webm)$/, ''), options);
    }


    /**
     * Set the transformation to apply on each source
     * @function VideoTag#setSourceTransformation
     * @param {Object} an object with pairs of source type and source transformation
     * @returns {VideoTag} Returns this instance for chaining purposes.
     */

    VideoTag.prototype.setSourceTransformation = function(value) {
      this.transformation().sourceTransformation(value);
      return this;
    };


    /**
     * Set the source types to include in the video tag
     * @function VideoTag#setSourceTypes
     * @param {Array<string>} an array of source types
     * @returns {VideoTag} Returns this instance for chaining purposes.
     */

    VideoTag.prototype.setSourceTypes = function(value) {
      this.transformation().sourceTypes(value);
      return this;
    };


    /**
     * Set the poster to be used in the video tag
     * @function VideoTag#setPoster
     * @param {string|Object} value
     * - string: a URL to use for the poster
     * - Object: transformation parameters to apply to the poster. May optionally include a public_id to use instead of the video public_id.
     * @returns {VideoTag} Returns this instance for chaining purposes.
     */

    VideoTag.prototype.setPoster = function(value) {
      this.transformation().poster(value);
      return this;
    };


    /**
     * Set the content to use as fallback in the video tag
     * @function VideoTag#setFallbackContent
     * @param {string} value - the content to use, in HTML format
     * @returns {VideoTag} Returns this instance for chaining purposes.
     */

    VideoTag.prototype.setFallbackContent = function(value) {
      this.transformation().fallbackContent(value);
      return this;
    };

    VideoTag.prototype.content = function() {
      var cld, fallback, innerTags, mimeType, sourceTransformation, sourceTypes, src, srcType, transformation, videoType;
      sourceTypes = this.transformation().getValue('source_types');
      sourceTransformation = this.transformation().getValue('source_transformation');
      fallback = this.transformation().getValue('fallback_content');
      if (Util.isArray(sourceTypes)) {
        cld = new Cloudinary(this.getOptions());
        innerTags = (function() {
          var j, len, results;
          results = [];
          for (j = 0, len = sourceTypes.length; j < len; j++) {
            srcType = sourceTypes[j];
            transformation = sourceTransformation[srcType] || {};
            src = cld.url("" + this.publicId, Util.defaults({}, transformation, {
              resource_type: 'video',
              format: srcType
            }));
            videoType = srcType === 'ogv' ? 'ogg' : srcType;
            mimeType = 'video/' + videoType;
            results.push("<source " + (this.htmlAttrs({
              src: src,
              type: mimeType
            })) + ">");
          }
          return results;
        }).call(this);
      } else {
        innerTags = [];
      }
      return innerTags.join('') + fallback;
    };

    VideoTag.prototype.attributes = function() {
      var a, attr, j, len, poster, ref, ref1, sourceTypes;
      sourceTypes = this.getOption('source_types');
      poster = (ref = this.getOption('poster')) != null ? ref : {};
      if (Util.isPlainObject(poster)) {
        defaults = poster.public_id != null ? Cloudinary.DEFAULT_IMAGE_PARAMS : DEFAULT_POSTER_OPTIONS;
        poster = new Cloudinary(this.getOptions()).url((ref1 = poster.public_id) != null ? ref1 : this.publicId, Util.defaults({}, poster, defaults));
      }
      attr = VideoTag.__super__.attributes.call(this) || [];
      for (j = 0, len = attr.length; j < len; j++) {
        a = attr[j];
        if (!Util.contains(VIDEO_TAG_PARAMS)) {
          attr = a;
        }
      }
      if (!Util.isArray(sourceTypes)) {
        attr["src"] = new Cloudinary(this.getOptions()).url(this.publicId, {
          resource_type: 'video',
          format: sourceTypes
        });
      }
      if (poster != null) {
        attr["poster"] = poster;
      }
      return attr;
    };

    return VideoTag;

  })(HtmlTag);

  /**
   * Image Tag
   * Depends on 'tags/htmltag', 'cloudinary'
   */
  ClientHintsMetaTag = (function(superClass) {
    extend(ClientHintsMetaTag, superClass);


    /**
     * Creates an HTML (DOM) Meta tag that enables client-hints.
     * @constructor ClientHintsMetaTag
     * @extends HtmlTag
     */

    function ClientHintsMetaTag(options) {
      ClientHintsMetaTag.__super__.constructor.call(this, 'meta', void 0, Util.assign({
        "http-equiv": "Accept-CH",
        content: "DPR, Viewport-Width, Width"
      }, options));
    }


    /** @override */

    ClientHintsMetaTag.prototype.closeTag = function() {
      return "";
    };

    return ClientHintsMetaTag;

  })(HtmlTag);
  Cloudinary = (function() {
    var AKAMAI_SHARED_CDN, CF_SHARED_CDN, DEFAULT_POSTER_OPTIONS, DEFAULT_VIDEO_SOURCE_TYPES, OLD_AKAMAI_SHARED_CDN, SEO_TYPES, SHARED_CDN, VERSION, absolutize, applyBreakpoints, cdnSubdomainNumber, closestAbove, cloudinaryUrlPrefix, defaultBreakpoints, finalizeResourceType, findContainerWidth, maxWidth, updateDpr;

    VERSION = "2.5.0";

    CF_SHARED_CDN = "d3jpl91pxevbkh.cloudfront.net";

    OLD_AKAMAI_SHARED_CDN = "cloudinary-a.akamaihd.net";

    AKAMAI_SHARED_CDN = "res.cloudinary.com";

    SHARED_CDN = AKAMAI_SHARED_CDN;

    DEFAULT_POSTER_OPTIONS = {
      format: 'jpg',
      resource_type: 'video'
    };

    DEFAULT_VIDEO_SOURCE_TYPES = ['webm', 'mp4', 'ogv'];

    SEO_TYPES = {
      "image/upload": "images",
      "image/private": "private_images",
      "image/authenticated": "authenticated_images",
      "raw/upload": "files",
      "video/upload": "videos"
    };


    /**
    * @const {Object} Cloudinary.DEFAULT_IMAGE_PARAMS
    * Defaults values for image parameters.
    *
    * (Previously defined using option_consume() )
     */

    Cloudinary.DEFAULT_IMAGE_PARAMS = {
      resource_type: "image",
      transformation: [],
      type: 'upload'
    };


    /**
    * Defaults values for video parameters.
    * @const {Object} Cloudinary.DEFAULT_VIDEO_PARAMS
    * (Previously defined using option_consume() )
     */

    Cloudinary.DEFAULT_VIDEO_PARAMS = {
      fallback_content: '',
      resource_type: "video",
      source_transformation: {},
      source_types: DEFAULT_VIDEO_SOURCE_TYPES,
      transformation: [],
      type: 'upload'
    };


    /**
     * Main Cloudinary class
     * @class Cloudinary
     * @param {Object} options - options to configure Cloudinary
     * @see Configuration for more details
     * @example
     *    var cl = new cloudinary.Cloudinary( { cloud_name: "mycloud"});
     *    var imgTag = cl.image("myPicID");
     */

    function Cloudinary(options) {
      var configuration;
      this.devicePixelRatioCache = {};
      this.responsiveConfig = {};
      this.responsiveResizeInitialized = false;
      configuration = new Configuration(options);
      this.config = function(newConfig, newValue) {
        return configuration.config(newConfig, newValue);
      };

      /**
       * Use \<meta\> tags in the document to configure this Cloudinary instance.
       * @return {Cloudinary} this for chaining
       */
      this.fromDocument = function() {
        configuration.fromDocument();
        return this;
      };

      /**
       * Use environment variables to configure this Cloudinary instance.
       * @return {Cloudinary} this for chaining
       */
      this.fromEnvironment = function() {
        configuration.fromEnvironment();
        return this;
      };

      /**
       * Initialize configuration.
       * @function Cloudinary#init
       * @see Configuration#init
       * @return {Cloudinary} this for chaining
       */
      this.init = function() {
        configuration.init();
        return this;
      };
    }


    /**
     * Convenience constructor
     * @param {Object} options
     * @return {Cloudinary}
     * @example cl = cloudinary.Cloudinary.new( { cloud_name: "mycloud"})
     */

    Cloudinary["new"] = function(options) {
      return new this(options);
    };


    /**
     * Return the resource type and action type based on the given configuration
     * @function Cloudinary#finalizeResourceType
     * @param {Object|string} resourceType
     * @param {string} [type='upload']
     * @param {string} [urlSuffix]
     * @param {boolean} [useRootPath]
     * @param {boolean} [shorten]
     * @returns {string} resource_type/type
     * @ignore
     */

    finalizeResourceType = function(resourceType, type, urlSuffix, useRootPath, shorten) {
      var key, options;
      if (resourceType == null) {
        resourceType = "image";
      }
      if (type == null) {
        type = "upload";
      }
      if (Util.isPlainObject(resourceType)) {
        options = resourceType;
        resourceType = options.resource_type;
        type = options.type;
        urlSuffix = options.url_suffix;
        useRootPath = options.use_root_path;
        shorten = options.shorten;
      }
      if (type == null) {
        type = 'upload';
      }
      if (urlSuffix != null) {
        resourceType = SEO_TYPES[resourceType + "/" + type];
        type = null;
        if (resourceType == null) {
          throw new Error("URL Suffix only supported for " + (((function() {
            var results;
            results = [];
            for (key in SEO_TYPES) {
              results.push(key);
            }
            return results;
          })()).join(', ')));
        }
      }
      if (useRootPath) {
        if (resourceType === 'image' && type === 'upload' || resourceType === "images") {
          resourceType = null;
          type = null;
        } else {
          throw new Error("Root path only supported for image/upload");
        }
      }
      if (shorten && resourceType === 'image' && type === 'upload') {
        resourceType = 'iu';
        type = null;
      }
      return [resourceType, type].join("/");
    };

    absolutize = function(url) {
      var prefix;
      if (!url.match(/^https?:\//)) {
        prefix = document.location.protocol + '//' + document.location.host;
        if (url[0] === '?') {
          prefix += document.location.pathname;
        } else if (url[0] !== '/') {
          prefix += document.location.pathname.replace(/\/[^\/]*$/, '/');
        }
        url = prefix + url;
      }
      return url;
    };


    /**
     * Generate an resource URL.
     * @function Cloudinary#url
     * @param {string} publicId - the public ID of the resource
     * @param {Object} [options] - options for the tag and transformations, possible values include all {@link Transformation} parameters
     *                          and {@link Configuration} parameters
     * @param {string} [options.type='upload'] - the classification of the resource
     * @param {Object} [options.resource_type='image'] - the type of the resource
     * @return {string} The resource URL
     */

    Cloudinary.prototype.url = function(publicId, options) {
      var error, error1, prefix, ref, resourceTypeAndType, transformation, transformationString, url, version;
      if (options == null) {
        options = {};
      }
      if (!publicId) {
        return publicId;
      }
      if (options instanceof Transformation) {
        options = options.toOptions();
      }
      options = Util.defaults({}, options, this.config(), Cloudinary.DEFAULT_IMAGE_PARAMS);
      if (options.type === 'fetch') {
        options.fetch_format = options.fetch_format || options.format;
        publicId = absolutize(publicId);
      }
      transformation = new Transformation(options);
      transformationString = transformation.serialize();
      if (!options.cloud_name) {
        throw 'Unknown cloud_name';
      }
      if (publicId.search('/') >= 0 && !publicId.match(/^v[0-9]+/) && !publicId.match(/^https?:\//) && !((ref = options.version) != null ? ref.toString() : void 0)) {
        options.version = 1;
      }
      if (publicId.match(/^https?:/)) {
        if (options.type === 'upload' || options.type === 'asset') {
          url = publicId;
        } else {
          publicId = encodeURIComponent(publicId).replace(/%3A/g, ':').replace(/%2F/g, '/');
        }
      } else {
        try {
          publicId = decodeURIComponent(publicId);
        } catch (error1) {
          error = error1;
        }
        publicId = encodeURIComponent(publicId).replace(/%3A/g, ':').replace(/%2F/g, '/');
        if (options.url_suffix) {
          if (options.url_suffix.match(/[\.\/]/)) {
            throw 'url_suffix should not include . or /';
          }
          publicId = publicId + '/' + options.url_suffix;
        }
        if (options.format) {
          if (!options.trust_public_id) {
            publicId = publicId.replace(/\.(jpg|png|gif|webp)$/, '');
          }
          publicId = publicId + '.' + options.format;
        }
      }
      prefix = cloudinaryUrlPrefix(publicId, options);
      resourceTypeAndType = finalizeResourceType(options.resource_type, options.type, options.url_suffix, options.use_root_path, options.shorten);
      version = options.version ? 'v' + options.version : '';
      return url || Util.compact([prefix, resourceTypeAndType, transformationString, version, publicId]).join('/').replace(/([^:])\/+/g, '$1/');
    };


    /**
     * Generate an video resource URL.
     * @function Cloudinary#video_url
     * @param {string} publicId - the public ID of the resource
     * @param {Object} [options] - options for the tag and transformations, possible values include all {@link Transformation} parameters
     *                          and {@link Configuration} parameters
     * @param {string} [options.type='upload'] - the classification of the resource
     * @return {string} The video URL
     */

    Cloudinary.prototype.video_url = function(publicId, options) {
      options = Util.assign({
        resource_type: 'video'
      }, options);
      return this.url(publicId, options);
    };


    /**
     * Generate an video thumbnail URL.
     * @function Cloudinary#video_thumbnail_url
     * @param {string} publicId - the public ID of the resource
     * @param {Object} [options] - options for the tag and transformations, possible values include all {@link Transformation} parameters
     *                          and {@link Configuration} parameters
     * @param {string} [options.type='upload'] - the classification of the resource
     * @return {string} The video thumbnail URL
     */

    Cloudinary.prototype.video_thumbnail_url = function(publicId, options) {
      options = Util.assign({}, DEFAULT_POSTER_OPTIONS, options);
      return this.url(publicId, options);
    };


    /**
     * Generate a string representation of the provided transformation options.
     * @function Cloudinary#transformation_string
     * @param {Object} options - the transformation options
     * @returns {string} The transformation string
     */

    Cloudinary.prototype.transformation_string = function(options) {
      return new Transformation(options).serialize();
    };


    /**
     * Generate an image tag.
     * @function Cloudinary#image
     * @param {string} publicId - the public ID of the image
     * @param {Object} [options] - options for the tag and transformations
     * @return {HTMLImageElement} an image tag element
     */

    Cloudinary.prototype.image = function(publicId, options) {
      var client_hints, img, ref, ref1;
      if (options == null) {
        options = {};
      }
      img = this.imageTag(publicId, options);
      client_hints = (ref = (ref1 = options.client_hints) != null ? ref1 : this.config('client_hints')) != null ? ref : false;
      if (!((options.src != null) || client_hints)) {
        img.setAttr("src", '');
      }
      img = img.toDOM();
      if (!client_hints) {
        Util.setData(img, 'src-cache', this.url(publicId, options));
        this.cloudinary_update(img, options);
      }
      return img;
    };


    /**
     * Creates a new ImageTag instance, configured using this own's configuration.
     * @function Cloudinary#imageTag
     * @param {string} publicId - the public ID of the resource
     * @param {Object} options - additional options to pass to the new ImageTag instance
     * @return {ImageTag} An ImageTag that is attached (chained) to this Cloudinary instance
     */

    Cloudinary.prototype.imageTag = function(publicId, options) {
      var tag;
      tag = new ImageTag(publicId, this.config());
      tag.transformation().fromOptions(options);
      return tag;
    };


    /**
     * Generate an image tag for the video thumbnail.
     * @function Cloudinary#video_thumbnail
     * @param {string} publicId - the public ID of the video
     * @param {Object} [options] - options for the tag and transformations
     * @return {HTMLImageElement} An image tag element
     */

    Cloudinary.prototype.video_thumbnail = function(publicId, options) {
      return this.image(publicId, Util.merge({}, DEFAULT_POSTER_OPTIONS, options));
    };


    /**
     * @function Cloudinary#facebook_profile_image
     * @param {string} publicId - the public ID of the image
     * @param {Object} [options] - options for the tag and transformations
     * @return {HTMLImageElement} an image tag element
     */

    Cloudinary.prototype.facebook_profile_image = function(publicId, options) {
      return this.image(publicId, Util.assign({
        type: 'facebook'
      }, options));
    };


    /**
     * @function Cloudinary#twitter_profile_image
     * @param {string} publicId - the public ID of the image
     * @param {Object} [options] - options for the tag and transformations
     * @return {HTMLImageElement} an image tag element
     */

    Cloudinary.prototype.twitter_profile_image = function(publicId, options) {
      return this.image(publicId, Util.assign({
        type: 'twitter'
      }, options));
    };


    /**
     * @function Cloudinary#twitter_name_profile_image
     * @param {string} publicId - the public ID of the image
     * @param {Object} [options] - options for the tag and transformations
     * @return {HTMLImageElement} an image tag element
     */

    Cloudinary.prototype.twitter_name_profile_image = function(publicId, options) {
      return this.image(publicId, Util.assign({
        type: 'twitter_name'
      }, options));
    };


    /**
     * @function Cloudinary#gravatar_image
     * @param {string} publicId - the public ID of the image
     * @param {Object} [options] - options for the tag and transformations
     * @return {HTMLImageElement} an image tag element
     */

    Cloudinary.prototype.gravatar_image = function(publicId, options) {
      return this.image(publicId, Util.assign({
        type: 'gravatar'
      }, options));
    };


    /**
     * @function Cloudinary#fetch_image
     * @param {string} publicId - the public ID of the image
     * @param {Object} [options] - options for the tag and transformations
     * @return {HTMLImageElement} an image tag element
     */

    Cloudinary.prototype.fetch_image = function(publicId, options) {
      return this.image(publicId, Util.assign({
        type: 'fetch'
      }, options));
    };


    /**
     * @function Cloudinary#video
     * @param {string} publicId - the public ID of the image
     * @param {Object} [options] - options for the tag and transformations
     * @return {HTMLImageElement} an image tag element
     */

    Cloudinary.prototype.video = function(publicId, options) {
      if (options == null) {
        options = {};
      }
      return this.videoTag(publicId, options).toHtml();
    };


    /**
     * Creates a new VideoTag instance, configured using this own's configuration.
     * @function Cloudinary#videoTag
     * @param {string} publicId - the public ID of the resource
     * @param {Object} options - additional options to pass to the new VideoTag instance
     * @return {VideoTag} A VideoTag that is attached (chained) to this Cloudinary instance
     */

    Cloudinary.prototype.videoTag = function(publicId, options) {
      options = Util.defaults({}, options, this.config());
      return new VideoTag(publicId, options);
    };


    /**
     * Generate the URL of the sprite image
     * @function Cloudinary#sprite_css
     * @param {string} publicId - the public ID of the resource
     * @param {Object} [options] - options for the tag and transformations
     * @see {@link http://cloudinary.com/documentation/sprite_generation Sprite generation}
     */

    Cloudinary.prototype.sprite_css = function(publicId, options) {
      options = Util.assign({
        type: 'sprite'
      }, options);
      if (!publicId.match(/.css$/)) {
        options.format = 'css';
      }
      return this.url(publicId, options);
    };


    /**
    * Initialize the responsive behaviour.<br>
    * Calls {@link Cloudinary#cloudinary_update} to modify image tags.
     * @function Cloudinary#responsive
    * @param {Object} options
    * @param {String} [options.responsive_class='cld-responsive'] - provide an alternative class used to locate img tags
    * @param {number} [options.responsive_debounce=100] - the debounce interval in milliseconds.
    * @param {boolean} [bootstrap=true] if true processes the img tags by calling cloudinary_update. When false the tags will be processed only after a resize event.
    * @see {@link Cloudinary#cloudinary_update} for additional configuration parameters
     */

    Cloudinary.prototype.responsive = function(options, bootstrap) {
      var ref, ref1, ref2, responsiveClass, responsiveResize, timeout;
      if (bootstrap == null) {
        bootstrap = true;
      }
      this.responsiveConfig = Util.merge(this.responsiveConfig || {}, options);
      responsiveClass = (ref = this.responsiveConfig['responsive_class']) != null ? ref : this.config('responsive_class');
      if (bootstrap) {
        this.cloudinary_update("img." + responsiveClass + ", img.cld-hidpi", this.responsiveConfig);
      }
      responsiveResize = (ref1 = (ref2 = this.responsiveConfig['responsive_resize']) != null ? ref2 : this.config('responsive_resize')) != null ? ref1 : true;
      if (responsiveResize && !this.responsiveResizeInitialized) {
        this.responsiveConfig.resizing = this.responsiveResizeInitialized = true;
        timeout = null;
        return window.addEventListener('resize', (function(_this) {
          return function() {
            var debounce, ref3, ref4, reset, run, wait, waitFunc;
            debounce = (ref3 = (ref4 = _this.responsiveConfig['responsive_debounce']) != null ? ref4 : _this.config('responsive_debounce')) != null ? ref3 : 100;
            reset = function() {
              if (timeout) {
                clearTimeout(timeout);
                return timeout = null;
              }
            };
            run = function() {
              return _this.cloudinary_update("img." + responsiveClass, _this.responsiveConfig);
            };
            waitFunc = function() {
              reset();
              return run();
            };
            wait = function() {
              reset();
              return timeout = setTimeout(waitFunc, debounce);
            };
            if (debounce) {
              return wait();
            } else {
              return run();
            }
          };
        })(this));
      }
    };


    /**
     * @function Cloudinary#calc_breakpoint
     * @private
     * @ignore
     */

    Cloudinary.prototype.calc_breakpoint = function(element, width, steps) {
      var breakpoints, point;
      breakpoints = Util.getData(element, 'breakpoints') || Util.getData(element, 'stoppoints') || this.config('breakpoints') || this.config('stoppoints') || defaultBreakpoints;
      if (Util.isFunction(breakpoints)) {
        return breakpoints(width, steps);
      } else {
        if (Util.isString(breakpoints)) {
          breakpoints = ((function() {
            var j, len, ref, results;
            ref = breakpoints.split(',');
            results = [];
            for (j = 0, len = ref.length; j < len; j++) {
              point = ref[j];
              results.push(parseInt(point));
            }
            return results;
          })()).sort(function(a, b) {
            return a - b;
          });
        }
        return closestAbove(breakpoints, width);
      }
    };


    /**
     * @function Cloudinary#calc_stoppoint
     * @deprecated Use {@link calc_breakpoint} instead.
     * @private
     * @ignore
     */

    Cloudinary.prototype.calc_stoppoint = Cloudinary.prototype.calc_breakpoint;


    /**
     * @function Cloudinary#device_pixel_ratio
     * @private
     */

    Cloudinary.prototype.device_pixel_ratio = function(roundDpr) {
      var dpr, dprString;
      if (roundDpr == null) {
        roundDpr = true;
      }
      dpr = (typeof window !== "undefined" && window !== null ? window.devicePixelRatio : void 0) || 1;
      if (roundDpr) {
        dpr = Math.ceil(dpr);
      }
      if (dpr <= 0 || dpr === NaN) {
        dpr = 1;
      }
      dprString = dpr.toString();
      if (dprString.match(/^\d+$/)) {
        dprString += '.0';
      }
      return dprString;
    };

    defaultBreakpoints = function(width, steps) {
      if (steps == null) {
        steps = 100;
      }
      return steps * Math.ceil(width / steps);
    };

    closestAbove = function(list, value) {
      var i;
      i = list.length - 2;
      while (i >= 0 && list[i] >= value) {
        i--;
      }
      return list[i + 1];
    };

    cdnSubdomainNumber = function(publicId) {
      return crc32(publicId) % 5 + 1;
    };

    cloudinaryUrlPrefix = function(publicId, options) {
      var cdnPart, host, path, protocol, ref, subdomain;
      if (((ref = options.cloud_name) != null ? ref.indexOf("/") : void 0) === 0) {
        return '/res' + options.cloud_name;
      }
      protocol = "http://";
      cdnPart = "";
      subdomain = "res";
      host = ".cloudinary.com";
      path = "/" + options.cloud_name;
      if (options.protocol) {
        protocol = options.protocol + '//';
      }
      if (options.private_cdn) {
        cdnPart = options.cloud_name + "-";
        path = "";
      }
      if (options.cdn_subdomain) {
        subdomain = "res-" + cdnSubdomainNumber(publicId);
      }
      if (options.secure) {
        protocol = "https://";
        if (options.secure_cdn_subdomain === false) {
          subdomain = "res";
        }
        if ((options.secure_distribution != null) && options.secure_distribution !== OLD_AKAMAI_SHARED_CDN && options.secure_distribution !== SHARED_CDN) {
          cdnPart = "";
          subdomain = "";
          host = options.secure_distribution;
        }
      } else if (options.cname) {
        protocol = "http://";
        cdnPart = "";
        subdomain = options.cdn_subdomain ? 'a' + ((crc32(publicId) % 5) + 1) + '.' : '';
        host = options.cname;
      }
      return [protocol, cdnPart, subdomain, host, path].join("");
    };


    /**
    * Finds all `img` tags under each node and sets it up to provide the image through Cloudinary
    * @param {Element[]} nodes the parent nodes to search for img under
    * @param {Object} [options={}] options and transformations params
    * @function Cloudinary#processImageTags
     */

    Cloudinary.prototype.processImageTags = function(nodes, options) {
      var images, imgOptions, node, publicId, url;
      if (options == null) {
        options = {};
      }
      if (Util.isEmpty(nodes)) {
        return this;
      }
      options = Util.defaults({}, options, this.config());
      images = (function() {
        var j, len, ref, results;
        results = [];
        for (j = 0, len = nodes.length; j < len; j++) {
          node = nodes[j];
          if (!(((ref = node.tagName) != null ? ref.toUpperCase() : void 0) === 'IMG')) {
            continue;
          }
          imgOptions = Util.assign({
            width: node.getAttribute('width'),
            height: node.getAttribute('height'),
            src: node.getAttribute('src')
          }, options);
          publicId = imgOptions['source'] || imgOptions['src'];
          delete imgOptions['source'];
          delete imgOptions['src'];
          url = this.url(publicId, imgOptions);
          imgOptions = new Transformation(imgOptions).toHtmlAttributes();
          Util.setData(node, 'src-cache', url);
          node.setAttribute('width', imgOptions.width);
          node.setAttribute('height', imgOptions.height);
          results.push(node);
        }
        return results;
      }).call(this);
      this.cloudinary_update(images, options);
      return this;
    };

    applyBreakpoints = function(tag, width, steps, options) {
      var ref, ref1, ref2, responsive_use_breakpoints;
      responsive_use_breakpoints = (ref = (ref1 = (ref2 = options['responsive_use_breakpoints']) != null ? ref2 : options['responsive_use_stoppoints']) != null ? ref1 : this.config('responsive_use_breakpoints')) != null ? ref : this.config('responsive_use_stoppoints');
      if ((!responsive_use_breakpoints) || (responsive_use_breakpoints === 'resize' && !options.resizing)) {
        return width;
      } else {
        return this.calc_breakpoint(tag, width, steps);
      }
    };

    findContainerWidth = function(element) {
      var containerWidth, style;
      containerWidth = 0;
      while (((element = element != null ? element.parentNode : void 0) instanceof Element) && !containerWidth) {
        style = window.getComputedStyle(element);
        if (!/^inline/.test(style.display)) {
          containerWidth = Util.width(element);
        }
      }
      return containerWidth;
    };

    updateDpr = function(dataSrc, roundDpr) {
      return dataSrc.replace(/\bdpr_(1\.0|auto)\b/g, 'dpr_' + this.device_pixel_ratio(roundDpr));
    };

    maxWidth = function(requiredWidth, tag) {
      var imageWidth;
      imageWidth = Util.getData(tag, 'width') || 0;
      if (requiredWidth > imageWidth) {
        imageWidth = requiredWidth;
        Util.setData(tag, 'width', requiredWidth);
      }
      return imageWidth;
    };


    /**
    * Update hidpi (dpr_auto) and responsive (w_auto) fields according to the current container size and the device pixel ratio.
    * Only images marked with the cld-responsive class have w_auto updated.
    * @function Cloudinary#cloudinary_update
    * @param {(Array|string|NodeList)} elements - the elements to modify
    * @param {Object} options
    * @param {boolean|string} [options.responsive_use_breakpoints=true]
    *  - when `true`, always use breakpoints for width
    * - when `"resize"` use exact width on first render and breakpoints on resize
    * - when `false` always use exact width
    * @param {boolean} [options.responsive] - if `true`, enable responsive on this element. Can be done by adding cld-responsive.
    * @param {boolean} [options.responsive_preserve_height] - if set to true, original css height is preserved.
    *   Should only be used if the transformation supports different aspect ratios.
     */

    Cloudinary.prototype.cloudinary_update = function(elements, options) {
      var containerWidth, dataSrc, j, len, match, ref, ref1, ref2, ref3, ref4, ref5, requiredWidth, responsive, responsiveClass, roundDpr, setUrl, tag;
      if (options == null) {
        options = {};
      }
      if (elements === null) {
        return this;
      }
      responsive = (ref = (ref1 = options.responsive) != null ? ref1 : this.config('responsive')) != null ? ref : false;
      elements = (function() {
        switch (false) {
          case !Util.isArray(elements):
            return elements;
          case elements.constructor.name !== "NodeList":
            return elements;
          case !Util.isString(elements):
            return document.querySelectorAll(elements);
          default:
            return [elements];
        }
      })();
      responsiveClass = (ref2 = (ref3 = this.responsiveConfig['responsive_class']) != null ? ref3 : options['responsive_class']) != null ? ref2 : this.config('responsive_class');
      roundDpr = (ref4 = options['round_dpr']) != null ? ref4 : this.config('round_dpr');
      for (j = 0, len = elements.length; j < len; j++) {
        tag = elements[j];
        if (!((ref5 = tag.tagName) != null ? ref5.match(/img/i) : void 0)) {
          continue;
        }
        setUrl = true;
        if (responsive) {
          Util.addClass(tag, responsiveClass);
        }
        dataSrc = Util.getData(tag, 'src-cache') || Util.getData(tag, 'src');
        if (!Util.isEmpty(dataSrc)) {
          dataSrc = updateDpr.call(this, dataSrc, roundDpr);
          if (HtmlTag.isResponsive(tag, responsiveClass)) {
            containerWidth = findContainerWidth(tag);
            if (containerWidth !== 0) {
              switch (false) {
                case !/w_auto:breakpoints/.test(dataSrc):
                  requiredWidth = maxWidth(containerWidth, tag);
                  dataSrc = dataSrc.replace(/w_auto:breakpoints([_0-9]*)(:[0-9]+)?/, "w_auto:breakpoints$1:" + requiredWidth);
                  break;
                case !(match = /w_auto(:(\d+))?/.exec(dataSrc)):
                  requiredWidth = applyBreakpoints.call(this, tag, containerWidth, match[2], options);
                  requiredWidth = maxWidth(requiredWidth, tag);
                  dataSrc = dataSrc.replace(/w_auto[^,\/]*/g, "w_" + requiredWidth);
              }
              Util.removeAttribute(tag, 'width');
              if (!options.responsive_preserve_height) {
                Util.removeAttribute(tag, 'height');
              }
            } else {
              setUrl = false;
            }
          }
          if (setUrl) {
            Util.setAttribute(tag, 'src', dataSrc);
          }
        }
      }
      return this;
    };


    /**
     * Provide a transformation object, initialized with own's options, for chaining purposes.
     * @function Cloudinary#transformation
     * @param {Object} options
     * @return {Transformation}
     */

    Cloudinary.prototype.transformation = function(options) {
      return Transformation["new"](this.config()).fromOptions(options).setParent(this);
    };

    return Cloudinary;

  })();

  /**
   * Cloudinary jQuery plugin
   * Depends on 'jquery', 'util', 'transformation', 'cloudinary'
   */
  CloudinaryJQuery = (function(superClass) {
    extend(CloudinaryJQuery, superClass);


    /**
     * Cloudinary class with jQuery support
     * @constructor CloudinaryJQuery
     * @extends Cloudinary
     */

    function CloudinaryJQuery(options) {
      CloudinaryJQuery.__super__.constructor.call(this, options);
    }


    /**
     * @override
     */

    CloudinaryJQuery.prototype.image = function(publicId, options) {
      var client_hints, img, ref, ref1;
      if (options == null) {
        options = {};
      }
      img = this.imageTag(publicId, options);
      client_hints = (ref = (ref1 = options.client_hints) != null ? ref1 : this.config('client_hints')) != null ? ref : false;
      if (!((options.src != null) || client_hints)) {
        img.setAttr("src", '');
      }
      img = jQuery(img.toHtml());
      if (!client_hints) {
        img.data('src-cache', this.url(publicId, options)).cloudinary_update(options);
      }
      return img;
    };


    /**
     * @override
     */

    CloudinaryJQuery.prototype.responsive = function(options) {
      var ref, ref1, ref2, responsiveClass, responsiveConfig, responsiveResizeInitialized, responsive_resize, timeout;
      responsiveConfig = jQuery.extend(responsiveConfig || {}, options);
      responsiveClass = (ref = this.responsiveConfig['responsive_class']) != null ? ref : this.config('responsive_class');
      jQuery("img." + responsiveClass + ", img.cld-hidpi").cloudinary_update(responsiveConfig);
      responsive_resize = (ref1 = (ref2 = responsiveConfig['responsive_resize']) != null ? ref2 : this.config('responsive_resize')) != null ? ref1 : true;
      if (responsive_resize && !responsiveResizeInitialized) {
        responsiveConfig.resizing = responsiveResizeInitialized = true;
        timeout = null;
        return jQuery(window).on('resize', (function(_this) {
          return function() {
            var debounce, ref3, ref4, reset, run, wait;
            debounce = (ref3 = (ref4 = responsiveConfig['responsive_debounce']) != null ? ref4 : _this.config('responsive_debounce')) != null ? ref3 : 100;
            reset = function() {
              if (timeout) {
                clearTimeout(timeout);
                return timeout = null;
              }
            };
            run = function() {
              return jQuery("img." + responsiveClass).cloudinary_update(responsiveConfig);
            };
            wait = function() {
              reset();
              return setTimeout((function() {
                reset();
                return run();
              }), debounce);
            };
            if (debounce) {
              return wait();
            } else {
              return run();
            }
          };
        })(this));
      }
    };

    return CloudinaryJQuery;

  })(Cloudinary);

  /**
   * The following methods are provided through the jQuery class
   * @class jQuery
   */

  /**
   * Convert all img tags in the collection to utilize Cloudinary.
   * @function jQuery#cloudinary
   * @param {Object} [options] - options for the tag and transformations
   * @returns {jQuery}
   */
  jQuery.fn.cloudinary = function(options) {
    this.filter('img').each(function() {
      var img_options, public_id, url;
      img_options = jQuery.extend({
        width: jQuery(this).attr('width'),
        height: jQuery(this).attr('height'),
        src: jQuery(this).attr('src')
      }, jQuery(this).data(), options);
      public_id = img_options.source || img_options.src;
      delete img_options.source;
      delete img_options.src;
      url = jQuery.cloudinary.url(public_id, img_options);
      img_options = new Transformation(img_options).toHtmlAttributes();
      return jQuery(this).data('src-cache', url).attr({
        width: img_options.width,
        height: img_options.height
      });
    }).cloudinary_update(options);
    return this;
  };

  /**
   * Update hidpi (dpr_auto) and responsive (w_auto) fields according to the current container size and the device pixel ratio.
   * Only images marked with the cld-responsive class have w_auto updated.
   * options:
   * - responsive_use_stoppoints:
   *   - true - always use stoppoints for width
   *   - "resize" - use exact width on first render and stoppoints on resize (default)
   *   - false - always use exact width
   * - responsive:
   *   - true - enable responsive on this element. Can be done by adding cld-responsive.
   *            Note that jQuery.cloudinary.responsive() should be called once on the page.
   * - responsive_preserve_height: if set to true, original css height is perserved. Should only be used if the transformation supports different aspect ratios.
   */
  jQuery.fn.cloudinary_update = function(options) {
    if (options == null) {
      options = {};
    }
    jQuery.cloudinary.cloudinary_update(this.filter('img').toArray(), options);
    return this;
  };
  webp = null;

  /**
   * @function jQuery#webpify
   */
  jQuery.fn.webpify = function(options, webp_options) {
    var that, webp_canary;
    if (options == null) {
      options = {};
    }
    that = this;
    webp_options = webp_options != null ? webp_options : options;
    if (!webp) {
      webp = jQuery.Deferred();
      webp_canary = new Image;
      webp_canary.onerror = webp.reject;
      webp_canary.onload = webp.resolve;
      webp_canary.src = 'data:image/webp;base64,UklGRi4AAABXRUJQVlA4TCEAAAAvAUAAEB8wAiMwAgSSNtse/cXjxyCCmrYNWPwmHRH9jwMA';
    }
    jQuery(function() {
      return webp.done(function() {
        return jQuery(that).cloudinary(jQuery.extend({}, webp_options, {
          format: 'webp'
        }));
      }).fail(function() {
        return jQuery(that).cloudinary(options);
      });
    });
    return this;
  };
  jQuery.fn.fetchify = function(options) {
    return this.cloudinary(jQuery.extend(options, {
      'type': 'fetch'
    }));
  };
  jQuery.cloudinary = new CloudinaryJQuery();
  jQuery.cloudinary.fromDocument();

  /**
   * This module extends CloudinaryJquery to support jQuery File Upload
   * Depends on 'jquery', 'util', 'cloudinaryjquery', 'jquery.ui.widget', 'jquery.iframe-transport','jquery.fileupload'
   */

  /**
   * Delete a resource using the upload token
   * @function CloudinaryJQuery#delete_by_token
   * @param {string} delete_token - the delete token
   * @param {Object} [options]
   * @param {string} [options.url] - an alternative URL to use for the API
   * @param {string} [options.cloud_name] - an alternative cloud_name to use. This parameter is ignored if `options.url` is provided.
   */
  CloudinaryJQuery.prototype.delete_by_token = function(delete_token, options) {
    var cloud_name, dataType, url;
    options = options || {};
    url = options.url;
    if (!url) {
      cloud_name = options.cloud_name || jQuery.cloudinary.config().cloud_name;
      url = 'https://api.cloudinary.com/v1_1/' + cloud_name + '/delete_by_token';
    }
    dataType = jQuery.support.xhrFileUpload ? 'json' : 'iframe json';
    return jQuery.ajax({
      url: url,
      method: 'POST',
      data: {
        token: delete_token
      },
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      },
      dataType: dataType
    });
  };

  /**
   * Creates an `input` tag and sets it up to upload files to cloudinary
   * @function CloudinaryJQuery#unsigned_upload_tag
   * @param {string}
   */
  CloudinaryJQuery.prototype.unsigned_upload_tag = function(upload_preset, upload_params, options) {
    return jQuery('<input/>').attr({
      type: 'file',
      name: 'file'
    }).unsigned_cloudinary_upload(upload_preset, upload_params, options);
  };

  /**
   * Initialize the jQuery File Upload plugin to upload to Cloudinary
   * @function jQuery#cloudinary_fileupload
   * @param {Object} options
   * @returns {jQuery}
   */
  jQuery.fn.cloudinary_fileupload = function(options) {
    var cloud_name, initializing, resource_type, type, upload_url;
    if (!Util.isFunction(jQuery.fn.fileupload)) {
      return this;
    }
    initializing = !this.data('blueimpFileupload');
    if (initializing) {
      options = jQuery.extend({
        maxFileSize: 20000000,
        dataType: 'json',
        headers: {
          'X-Requested-With': 'XMLHttpRequest'
        }
      }, options);
    }
    this.fileupload(options);
    if (initializing) {
      this.bind('fileuploaddone', function(e, data) {
        var add_field, field, multiple, upload_info;
        if (data.result.error) {
          return;
        }
        data.result.path = ['v', data.result.version, '/', data.result.public_id, data.result.format ? '.' + data.result.format : ''].join('');
        if (data.cloudinaryField && data.form.length > 0) {
          upload_info = [data.result.resource_type, data.result.type, data.result.path].join('/') + '#' + data.result.signature;
          multiple = jQuery(e.target).prop('multiple');
          add_field = function() {
            return jQuery('<input/>').attr({
              type: 'hidden',
              name: data.cloudinaryField
            }).val(upload_info).appendTo(data.form);
          };
          if (multiple) {
            add_field();
          } else {
            field = jQuery(data.form).find('input[name="' + data.cloudinaryField + '"]');
            if (field.length > 0) {
              field.val(upload_info);
            } else {
              add_field();
            }
          }
        }
        return jQuery(e.target).trigger('cloudinarydone', data);
      });
      this.bind('fileuploadsend', function(e, data) {
        data.headers = jQuery.extend({}, data.headers, {
          'X-Unique-Upload-Id': (Math.random() * 10000000000).toString(16)
        });
        return true;
      });
      this.bind('fileuploadstart', function(e) {
        return jQuery(e.target).trigger('cloudinarystart');
      });
      this.bind('fileuploadstop', function(e) {
        return jQuery(e.target).trigger('cloudinarystop');
      });
      this.bind('fileuploadprogress', function(e, data) {
        return jQuery(e.target).trigger('cloudinaryprogress', data);
      });
      this.bind('fileuploadprogressall', function(e, data) {
        return jQuery(e.target).trigger('cloudinaryprogressall', data);
      });
      this.bind('fileuploadfail', function(e, data) {
        return jQuery(e.target).trigger('cloudinaryfail', data);
      });
      this.bind('fileuploadalways', function(e, data) {
        return jQuery(e.target).trigger('cloudinaryalways', data);
      });
      if (!this.fileupload('option').url) {
        cloud_name = options.cloud_name || jQuery.cloudinary.config().cloud_name;
        resource_type = options.resource_type || 'auto';
        type = options.type || 'upload';
        upload_url = 'https://api.cloudinary.com/v1_1/' + cloud_name + '/' + resource_type + '/' + type;
        this.fileupload('option', 'url', upload_url);
      }
    }
    return this;
  };

  /**
   * Add a file to upload
   * @function jQuery#cloudinary_upload_url
   * @param {string} remote_url - the url to add
   * @returns {jQuery}
   */
  jQuery.fn.cloudinary_upload_url = function(remote_url) {
    if (!Util.isFunction(jQuery.fn.fileupload)) {
      return this;
    }
    this.fileupload('option', 'formData').file = remote_url;
    this.fileupload('add', {
      files: [remote_url]
    });
    delete this.fileupload('option', 'formData').file;
    return this;
  };

  /**
   * Initialize the jQuery File Upload plugin to upload to Cloudinary using unsigned upload
   * @function jQuery#unsigned_cloudinary_upload
   * @param {string} upload_preset - the upload preset to use
   * @param {Object} [upload_params] - parameters that should be past to the server
   * @param {Object} [options]
   * @returns {jQuery}
   */
  jQuery.fn.unsigned_cloudinary_upload = function(upload_preset, upload_params, options) {
    var attr, attrs_to_move, html_options, i, key, value;
    if (upload_params == null) {
      upload_params = {};
    }
    if (options == null) {
      options = {};
    }
    upload_params = Util.cloneDeep(upload_params);
    options = Util.cloneDeep(options);
    attrs_to_move = ['cloud_name', 'resource_type', 'type'];
    i = 0;
    while (i < attrs_to_move.length) {
      attr = attrs_to_move[i];
      if (upload_params[attr]) {
        options[attr] = upload_params[attr];
        delete upload_params[attr];
      }
      i++;
    }
    for (key in upload_params) {
      value = upload_params[key];
      if (Util.isPlainObject(value)) {
        upload_params[key] = jQuery.map(value, function(v, k) {
          if (Util.isString(v)) {
            v = v.replace(/[\|=]/g, "\\$&");
          }
          return k + '=' + v;
        }).join('|');
      } else if (Util.isArray(value)) {
        if (value.length > 0 && jQuery.isArray(value[0])) {
          upload_params[key] = jQuery.map(value, function(array_value) {
            return array_value.join(',');
          }).join('|');
        } else {
          upload_params[key] = value.join(',');
        }
      }
    }
    if (!upload_params.callback) {
      upload_params.callback = '/cloudinary_cors.html';
    }
    upload_params.upload_preset = upload_preset;
    options.formData = upload_params;
    if (options.cloudinary_field) {
      options.cloudinaryField = options.cloudinary_field;
      delete options.cloudinary_field;
    }
    html_options = options.html || {};
    html_options["class"] = Util.trim("cloudinary_fileupload " + (html_options["class"] || ''));
    if (options.multiple) {
      html_options.multiple = true;
    }
    this.attr(html_options).cloudinary_fileupload(options);
    return this;
  };
  jQuery.cloudinary = new CloudinaryJQuery();
  cloudinary = {
    utf8_encode: utf8_encode,
    crc32: crc32,
    Util: Util,
    Condition: Condition,
    Transformation: Transformation,
    Configuration: Configuration,
    HtmlTag: HtmlTag,
    ImageTag: ImageTag,
    VideoTag: VideoTag,
    ClientHintsMetaTag: ClientHintsMetaTag,
    Layer: Layer,
    FetchLayer: FetchLayer,
    TextLayer: TextLayer,
    SubtitlesLayer: SubtitlesLayer,
    Cloudinary: Cloudinary,
    VERSION: "2.5.0",
    CloudinaryJQuery: CloudinaryJQuery
  };
  return cloudinary;
});


