<commit_before>/*!
 * jQuery Destaque - a simple slideshow plugin with built-in parallax effect
 * https://github.com/globocom/destaque
 * version: 0.1.0
 */

(function ($, window, document, undefined) {
  $.fn.destaque = function(params) {
    var params = $.extend({}, $.fn.destaque.options, params);
    return new Destaque(this, params);
  };

  $.fn.destaque.options = {
    currentSlide: 0,
    slideSpeed: 1000,
    slideMovement: 150,
    slideDirection: "toLeft",
    elementSpeed: 1000,
    autoSlideDelay: 3000,
    resumeSlideDelay: 250,
    stopOnMouseOver: true,
    easingType: "easeInOutExpo",
    itemDefaultZIndex: 10,
    itemSelector: "div.item",
    itemLoadedClass: "loaded",
    activeItemClass: "active",
    itemForegroundElementSelector: ".foreground img",

    // Callbacks
    onInit: function (slideshow) {},
    onResize: function (slideshow) {},
    onPause: function(slideshow) {},
    onResume: function(slideshow) {},
    onSlideLoad: function(slideshow, item, idx) {},
    beforePageUpdate: function(slideshow, pageData) {},
    onPageUpdate: function(slideshow, pageData) {}
  };

  var Destaque = function (element, params) {
    this.element = $(element);
    this.params = params;

    this.params.initialized = false;
    this.params.mouseOver = false;
    this.params.animating = false;

    this.params.autoId = 0;
    this.params.autoTimeStamp = 0;

    this._initElements();
    this._initListeners();

    this.params.onInit(this);
  };

  Destaque.prototype = {
    pause: function() {
      var params = this.params;

      if (!params.animating) {
        params.mouseOver = true;
        clearTimeout(params.autoId);
        params.onPause(this);
      }
    },

    resume: function() {
      var self = this;
      var params = this.params;

      if (!params.animating) {
        params.mouseOver = false;

        var timeout = 0;

        if (params.autoSlideDelay - (new Date().getTime() - params.autoTimeStamp) < 0) {
          timeout = params.resumeSlideDelay;
        } else {
          timeout = params.autoSlideDelay - (new Date().getTime() - params.autoTimeStamp);
        }

        params.autoId = setTimeout(function() {
          self._slideElementsOut();
        }, timeout);

        params.onResume(this);
      }
    },

    restart: function() {
      this.goTo(0);
    },

    slideSetAndMove: function(direction, targetToClear) {
      var params = this.params;

      if (!params.animating) {
        if (direction === "toLeft") {
          params.slideDirection = "toLeft";
          params.elementDirection = "fromLeft";
          this.element.removeClass("right").addClass("left");
        } else {
          params.slideDirection = "toRight";
          params.elementDirection = "fromRight";
          this.element.removeClass("left").addClass("right");
        }

        this._setElementPositions(true);
        this._slideElementsOut(targetToClear);
      }
    },

    goTo: function(slideNumber) {
      var params = this.params;
      var current = params.currentSlide;
      var currentSlide = this._currentSlide();

      if (slideNumber < 0 || slideNumber > params.slideSum) {
        return;
      }

      if (slideNumber > current || (current == params.slideSum && slideNumber == 0)) {
        params.currentSlide = slideNumber - 1;
        this.slideSetAndMove('toLeft', currentSlide);

      } else if (slideNumber < current) {
        params.currentSlide = slideNumber + 1;
        this.slideSetAndMove('toRight', currentSlide);
      }
    },

    refresh: function(newParams) {
      this.pause();
      this.params = $.extend({}, this.params, (newParams || {}));

      this.element.find(this.params.itemSelector + "." + this.params.activeItemClass).removeClass(this.params.activeItemClass);
      this.element.find(this.params.itemSelector).removeAttr("style").removeClass(this.params.itemLoadedClass).hide();
      this.element.find(this.params.itemSelector + " " + this.params.itemForegroundElementSelector).removeAttr("style");

      this.params.initialized = false;
      this._initElements();
      this.resume();
    },

    _initListeners: function() {
      this._initPaginationListeners();
      this._initMouseListeners();
      this._initKeyboardListeners();
      this._initMobileListeners();
      this._initWindowListeners();
    },

    _initPaginationListeners: function () {
      var self = this;

      if (!this.params.controlsSelector) {
        return;
      }
      $(this.params.controlsSelector).each(function() {
        $(this).bind("click.destaque", function(e) {
          e.preventDefault();

          var direction = $(this).attr("rel") === "prev" ? "toRight" : "toLeft";
          self.slideSetAndMove(direction);
        });
      });
    },

    _initMobileListeners: function() {
      var self = this;

      this.element.bind("swipeleft.destaque", function(e) {
        self.slideSetAndMove("toLeft");
       });

      this.element.bind("swiperight.destaque", function (e) {
        self.slideSetAndMove("toRight");
      });
    },

    _initMouseListeners: function () {
      var params = this.params;
      var self = this;

      if (params.slideSum > 1) {
        if (params.stopOnMouseOver) {
          this.element.mouseover(function() {
            self.pause();
          });

          this.element.mouseleave(function() {
            self.resume();
          });
        }
      }
    },

    _initKeyboardListeners: function() {
      var self = this;
      $("body").bind("keydown.destaque", function(e) {
        if (e.keyCode === 37) {
          self.slideSetAndMove("toRight");
        } else {
          if (e.keyCode === 39) {
            self.slideSetAndMove("toLeft");
          }
        }
      });
    },

    _initWindowListeners: function() {
      var self = this;

      $(window).bind("resize.destaque", function() {
        self.params.onResize(self);
      });
    },

    _initElements: function () {
      var element = this.element;
      var params = this.params;

      if (!params.initialized) {
        params.baseSize = element.width();
        params.slideSum = element.find(this.params.itemSelector).length;
        params.elementDirection = params.slideDirection === "toLeft" ? "fromLeft" : "toLeft";
        if (params.currentSlide < 0 || params.currentSlide >= params.slideSum) {
          params.currentSlide = 0;
        }

        this._initSlide();

        params.initialized = true;
      }
    },

    _initSlide: function() {
      var self = this;
      var params = this.params;

      this.element.find(params.itemSelector).each(function() {
        $(this).data("zIndex", params.itemDefaultZIndex).css({zIndex: params.itemDefaultZIndex});
      });

      this.element.find(params.itemForegroundElementSelector).each(function (idx, e) {
        var e = $(this);

        var initialX = parseInt(e.css("left"), 10) + (self.element.width() - params.baseSize) / 2;
        var initialY = parseInt(e.css("top"), 10);

        e.css({top: initialY, left: params.baseSize});
        e.data("xPos", initialX).data("yPos", initialY).data("slidePos", 9999);
      });

      this._loadSlide();
      this._currentSlide().addClass(params.activeItemClass).show();
      this._slideElementsIn();

      params.autoTimeStamp = new Date().getTime();
    },

    _setElementPositions: function(justCalculate) {
      var params = this.params;
      var element, pos = 0;

      this._currentSlide().find(params.itemForegroundElementSelector).each(function(i) {
        element = $(this);

        if (params.elementDirection === "fromLeft") {
          pos = params.baseSize + (i * params.baseSize) - (i > 0 ? parseInt(element.data("xPos"), 10) : 0);
        } else {
          pos = -params.baseSize - (i * params.baseSize) + (i > 0 ? parseInt(element.data("xPos"), 10) : 0);
        }

        element.data("slidePos", pos);

        if (!justCalculate) {
          element.css({left: pos});
        }
      });
    },

    _moveSlide: function(targetToClear) {
      var self = this;
      var params = this.params;

      var initialPosition = 0;
      var outPosition = 0;
      var current = this._currentSlide();
      var next = this._nextSlide();
      params.animating = true;

      if (params.slideDirection === "toLeft") {
        outPosition = -params.slideMovement;
        next.css({left: params.baseSize, zIndex: params.itemDefaultZIndex + 1}).show();
      } else {
        outPosition = params.slideMovement;
        next.css({left: -params.baseSize, zIndex: params.itemDefaultZIndex + 1}).show();
      }

      next.stop().animate({left: initialPosition}, params.slideSpeed, params.easingType, function() {
        next.addClass(params.activeItemClass);
      });

      this._clearTarget(current, outPosition);
      if (targetToClear) {
        this._clearTarget(targetToClear, outPosition);
      }

      this._updateCurrentSlide();
    },

    _clearTarget: function(target, outPosition) {
      var params = this.params;
      target.css({zIndex: params.itemDefaultZIndex}).stop().animate({left: outPosition}, params.slideSpeed, params.easingType, function() {
        $(this).removeClass(params.activeItemClass).hide();
      });
    },

    _updatePagers: function(callback) {
      var params = this.params;
      var data = {
        currentSlide: params.currentSlide,
        totalSlides:  params.slideSum
      };

      return params[callback](this, data);
    },

    _currentSlide: function() {
      var params = this.params;
      return this.element.find(params.itemSelector).eq(params.currentSlide);
    },

    _previousPage: function() {
      var params = this.params;

      if (params.slideDirection === "toLeft") {
        if (params.currentSlide > 0) {
          return params.currentSlide - 1;
        } else {
          return this.element.find(params.itemSelector).length - 1;
        }
      } else {
        if (params.currentSlide < params.slideSum - 1) {
          return params.currentSlide + 1;
        } else {
          return 0;
        }
      }
    },

    _nextPage: function(idx) {
      var params = this.params;

      if (params.slideDirection === "toLeft") {
        if (params.currentSlide < this.element.find(params.itemSelector).length - 1) {
          return params.currentSlide + 1;
        } else {
          return 0;
        }
      } else {
        if (params.currentSlide > 0) {
          return params.currentSlide - 1;
        } else {
          return this.element.find(params.itemSelector).length - 1;
        }
      }
    },

    _nextSlide: function() {
      return this.element.find(this.params.itemSelector).eq(this._nextPage());
    },

    _updateCurrentSlide: function() {
      this.params.currentSlide = this._nextPage();

      this._loadSlide();
      this._slideElementsIn();
    },

    _loadSlide: function() {
      var self = this;
      var params = this.params;

      var slidesIdx = [
        params.currentSlide,
        this._previousPage(),
        this._nextPage()
      ];

      var i, idx;
      for (i = 0; i < slidesIdx.length; i++) {
        idx = slidesIdx[i];

        this.element.find(params.itemSelector).eq(idx).each(function() {
          if (!$(this).hasClass(params.itemLoadedClass)) {
            $(this).addClass(params.itemLoadedClass);
            params.onSlideLoad(self, this, idx);
          }
        });
      }
    },

    _slideElementsIn: function() {
      var self = this;
      var params = this.params;

      var current = this._currentSlide();
      var elementNum = current.find(params.itemForegroundElementSelector).length;

      this._setElementPositions();

      current.each(function() {
        $(this).find(params.itemForegroundElementSelector).each(function(i) {
          if (!params.initialized) {
            $(this).css({left: $(this).data("xPos"), top: $(this).data("yPos")});

            if (elementNum - 1 === i && !params.mouseOver && params.slideSum > 1) {
              params.autoId = setTimeout(function() {
                self._slideElementsOut();
              }, params.autoSlideDelay);

              params.animating = false;
            }
          } else {
            params.animating = true;

            $(this).stop().css({left: $(this).data("slidePos"), top: $(this).data("yPos")});
            $(this).animate({left: $(this).data("xPos")}, params.elementSpeed, params.easingType, function() {
              if (elementNum - 1 === i && params.slideSum > 1) {
                if (!params.mouseOver) {
                  params.autoId = setTimeout(function() {
                    self._slideElementsOut();
                  }, params.autoSlideDelay);
                }

                params.autoTimeStamp = new Date().getTime();
                params.animating = false;
              }
            });
          }
        });
      });
    },

    _slideElementsOut: function(targetToClear) {
      var params = this.params;

      if (params.slideSum < 2) {
        return;
      }

      if (this._updatePagers("beforePageUpdate") === false) {
        return;
      };

      params.animating = true;
      clearTimeout(params.autoId);

      this.element.find(params.itemSelector + " " + params.itemForegroundElementSelector).removeAttr("style");
      this.element.find(params.itemSelector + "." + params.activeItemClass + " " + params.itemForegroundElementSelector).each(function() {
        var pos = params.elementDirection === "fromLeft" ? $(this).data("slidePos") * -1 + params.baseSize - $(this).width() : $(this).data("slidePos") * -1;
        $(this).stop().animate({left: pos}, params.elementSpeed, params.easingType);
      });

      this._moveSlide(targetToClear);
      this._updatePagers("onPageUpdate");
    }
  };
})(jQuery, window);<commit_msg>using context variables<commit_after>/*!
 * jQuery Destaque - a simple slideshow plugin with built-in parallax effect
 * https://github.com/globocom/destaque
 * version: 0.1.0
 */

;(function ($, window, document, undefined) {

  $.fn.destaque = function(params) {
    var params = $.extend({}, $.fn.destaque.options, params);
    return new Destaque(this, params);
  };

  $.fn.destaque.options = {
    currentSlide: 0,
    slideSpeed: 1000,
    slideMovement: 150,
    slideDirection: "toLeft",
    elementSpeed: 1000,
    autoSlideDelay: 3000,
    resumeSlideDelay: 250,
    stopOnMouseOver: true,
    easingType: "easeInOutExpo",
    itemDefaultZIndex: 10,
    itemSelector: "div.item",
    itemLoadedClass: "loaded",
    activeItemClass: "active",
    itemForegroundElementSelector: ".foreground img",

    // Callbacks
    onInit: function (slideshow) {},
    onResize: function (slideshow) {},
    onPause: function(slideshow) {},
    onResume: function(slideshow) {},
    onSlideLoad: function(slideshow, item, idx) {},
    beforePageUpdate: function(slideshow, pageData) {},
    onPageUpdate: function(slideshow, pageData) {}
  };

  var Destaque = function (element, params) {
    this.element = $(element);
    this.params = params;

    this.params.initialized = false;
    this.params.mouseOver = false;
    this.params.animating = false;

    this.params.autoId = 0;
    this.params.autoTimeStamp = 0;

    this._initElements();
    this._initListeners();

    this.params.onInit(this);
  };

  Destaque.prototype = {
    pause: function() {
      var params = this.params;

      if (!params.animating) {
        params.mouseOver = true;
        window.clearTimeout(params.autoId);
        params.onPause(this);
      }
    },

    resume: function() {
      var self = this;
      var params = this.params;

      if (!params.animating) {
        params.mouseOver = false;

        var timeout = 0;

        if (params.autoSlideDelay - (new Date().getTime() - params.autoTimeStamp) < 0) {
          timeout = params.resumeSlideDelay;
        } else {
          timeout = params.autoSlideDelay - (new Date().getTime() - params.autoTimeStamp);
        }

        params.autoId = window.setTimeout(function() {
          self._slideElementsOut();
        }, timeout);

        params.onResume(this);
      }
    },

    restart: function() {
      this.goTo(0);
    },

    slideSetAndMove: function(direction, targetToClear) {
      var params = this.params;

      if (!params.animating) {
        if (direction === "toLeft") {
          params.slideDirection = "toLeft";
          params.elementDirection = "fromLeft";
          this.element.removeClass("right").addClass("left");
        } else {
          params.slideDirection = "toRight";
          params.elementDirection = "fromRight";
          this.element.removeClass("left").addClass("right");
        }

        this._setElementPositions(true);
        this._slideElementsOut(targetToClear);
      }
    },

    goTo: function(slideNumber) {
      var params = this.params;
      var current = params.currentSlide;
      var currentSlide = this._currentSlide();

      if (slideNumber < 0 || slideNumber > params.slideSum) {
        return;
      }

      if (slideNumber > current || (current == params.slideSum && slideNumber == 0)) {
        params.currentSlide = slideNumber - 1;
        this.slideSetAndMove('toLeft', currentSlide);

      } else if (slideNumber < current) {
        params.currentSlide = slideNumber + 1;
        this.slideSetAndMove('toRight', currentSlide);
      }
    },

    refresh: function(newParams) {
      this.pause();
      this.params = $.extend({}, this.params, (newParams || {}));

      this.element.find(this.params.itemSelector + "." + this.params.activeItemClass).removeClass(this.params.activeItemClass);
      this.element.find(this.params.itemSelector).removeAttr("style").removeClass(this.params.itemLoadedClass).hide();
      this.element.find(this.params.itemSelector + " " + this.params.itemForegroundElementSelector).removeAttr("style");

      this.params.initialized = false;
      this._initElements();
      this.resume();
    },

    _initListeners: function() {
      this._initPaginationListeners();
      this._initMouseListeners();
      this._initKeyboardListeners();
      this._initMobileListeners();
      this._initWindowListeners();
    },

    _initPaginationListeners: function () {
      var self = this;

      if (!this.params.controlsSelector) {
        return;
      }
      $(this.params.controlsSelector).each(function() {
        $(this).bind("click.destaque", function(e) {
          e.preventDefault();

          var direction = $(this).attr("rel") === "prev" ? "toRight" : "toLeft";
          self.slideSetAndMove(direction);
        });
      });
    },

    _initMobileListeners: function() {
      var self = this;

      this.element.bind("swipeleft.destaque", function(e) {
        self.slideSetAndMove("toLeft");
       });

      this.element.bind("swiperight.destaque", function (e) {
        self.slideSetAndMove("toRight");
      });
    },

    _initMouseListeners: function () {
      var params = this.params;
      var self = this;

      if (params.slideSum > 1) {
        if (params.stopOnMouseOver) {
          this.element.mouseover(function() {
            self.pause();
          });

          this.element.mouseleave(function() {
            self.resume();
          });
        }
      }
    },

    _initKeyboardListeners: function() {
      var self = this;
      $("body").bind("keydown.destaque", function(e) {
        if (e.keyCode === 37) {
          self.slideSetAndMove("toRight");
        } else {
          if (e.keyCode === 39) {
            self.slideSetAndMove("toLeft");
          }
        }
      });
    },

    _initWindowListeners: function() {
      var self = this;

      $(window).bind("resize.destaque", function() {
        self.params.onResize(self);
      });
    },

    _initElements: function () {
      var element = this.element;
      var params = this.params;

      if (!params.initialized) {
        params.baseSize = element.width();
        params.slideSum = element.find(this.params.itemSelector).length;
        params.elementDirection = params.slideDirection === "toLeft" ? "fromLeft" : "toLeft";
        if (params.currentSlide < 0 || params.currentSlide >= params.slideSum) {
          params.currentSlide = 0;
        }

        this._initSlide();

        params.initialized = true;
      }
    },

    _initSlide: function() {
      var self = this;
      var params = this.params;

      this.element.find(params.itemSelector).each(function() {
        $(this).data("zIndex", params.itemDefaultZIndex).css({zIndex: params.itemDefaultZIndex});
      });

      this.element.find(params.itemForegroundElementSelector).each(function (idx, e) {
        var e = $(this);

        var initialX = parseInt(e.css("left"), 10) + (self.element.width() - params.baseSize) / 2;
        var initialY = parseInt(e.css("top"), 10);

        e.css({top: initialY, left: params.baseSize});
        e.data("xPos", initialX).data("yPos", initialY).data("slidePos", 9999);
      });

      this._loadSlide();
      this._currentSlide().addClass(params.activeItemClass).show();
      this._slideElementsIn();

      params.autoTimeStamp = new Date().getTime();
    },

    _setElementPositions: function(justCalculate) {
      var params = this.params;
      var element, pos = 0;

      this._currentSlide().find(params.itemForegroundElementSelector).each(function(i) {
        element = $(this);

        if (params.elementDirection === "fromLeft") {
          pos = params.baseSize + (i * params.baseSize) - (i > 0 ? parseInt(element.data("xPos"), 10) : 0);
        } else {
          pos = -params.baseSize - (i * params.baseSize) + (i > 0 ? parseInt(element.data("xPos"), 10) : 0);
        }

        element.data("slidePos", pos);

        if (!justCalculate) {
          element.css({left: pos});
        }
      });
    },

    _moveSlide: function(targetToClear) {
      var self = this;
      var params = this.params;

      var initialPosition = 0;
      var outPosition = 0;
      var current = this._currentSlide();
      var next = this._nextSlide();
      params.animating = true;

      if (params.slideDirection === "toLeft") {
        outPosition = -params.slideMovement;
        next.css({left: params.baseSize, zIndex: params.itemDefaultZIndex + 1}).show();
      } else {
        outPosition = params.slideMovement;
        next.css({left: -params.baseSize, zIndex: params.itemDefaultZIndex + 1}).show();
      }

      next.stop().animate({left: initialPosition}, params.slideSpeed, params.easingType, function() {
        next.addClass(params.activeItemClass);
      });

      this._clearTarget(current, outPosition);
      if (targetToClear) {
        this._clearTarget(targetToClear, outPosition);
      }

      this._updateCurrentSlide();
    },

    _clearTarget: function(target, outPosition) {
      var params = this.params;
      target.css({zIndex: params.itemDefaultZIndex}).stop().animate({left: outPosition}, params.slideSpeed, params.easingType, function() {
        $(this).removeClass(params.activeItemClass).hide();
      });
    },

    _updatePagers: function(callback) {
      var params = this.params;
      var data = {
        currentSlide: params.currentSlide,
        totalSlides:  params.slideSum
      };

      return params[callback](this, data);
    },

    _currentSlide: function() {
      var params = this.params;
      return this.element.find(params.itemSelector).eq(params.currentSlide);
    },

    _previousPage: function() {
      var params = this.params;

      if (params.slideDirection === "toLeft") {
        if (params.currentSlide > 0) {
          return params.currentSlide - 1;
        } else {
          return this.element.find(params.itemSelector).length - 1;
        }
      } else {
        if (params.currentSlide < params.slideSum - 1) {
          return params.currentSlide + 1;
        } else {
          return 0;
        }
      }
    },

    _nextPage: function(idx) {
      var params = this.params;

      if (params.slideDirection === "toLeft") {
        if (params.currentSlide < this.element.find(params.itemSelector).length - 1) {
          return params.currentSlide + 1;
        } else {
          return 0;
        }
      } else {
        if (params.currentSlide > 0) {
          return params.currentSlide - 1;
        } else {
          return this.element.find(params.itemSelector).length - 1;
        }
      }
    },

    _nextSlide: function() {
      return this.element.find(this.params.itemSelector).eq(this._nextPage());
    },

    _updateCurrentSlide: function() {
      this.params.currentSlide = this._nextPage();

      this._loadSlide();
      this._slideElementsIn();
    },

    _loadSlide: function() {
      var self = this;
      var params = this.params;

      var slidesIdx = [
        params.currentSlide,
        this._previousPage(),
        this._nextPage()
      ];

      var i, idx;
      for (i = 0; i < slidesIdx.length; i++) {
        idx = slidesIdx[i];

        this.element.find(params.itemSelector).eq(idx).each(function() {
          if (!$(this).hasClass(params.itemLoadedClass)) {
            $(this).addClass(params.itemLoadedClass);
            params.onSlideLoad(self, this, idx);
          }
        });
      }
    },

    _slideElementsIn: function() {
      var self = this;
      var params = this.params;

      var current = this._currentSlide();
      var elementNum = current.find(params.itemForegroundElementSelector).length;

      this._setElementPositions();

      current.each(function() {
        $(this).find(params.itemForegroundElementSelector).each(function(i) {
          if (!params.initialized) {
            $(this).css({left: $(this).data("xPos"), top: $(this).data("yPos")});

            if (elementNum - 1 === i && !params.mouseOver && params.slideSum > 1) {
              params.autoId = window.setTimeout(function() {
                self._slideElementsOut();
              }, params.autoSlideDelay);

              params.animating = false;
            }
          } else {
            params.animating = true;

            $(this).stop().css({left: $(this).data("slidePos"), top: $(this).data("yPos")});
            $(this).animate({left: $(this).data("xPos")}, params.elementSpeed, params.easingType, function() {
              if (elementNum - 1 === i && params.slideSum > 1) {
                if (!params.mouseOver) {
                  params.autoId = window.setTimeout(function() {
                    self._slideElementsOut();
                  }, params.autoSlideDelay);
                }

                params.autoTimeStamp = new Date().getTime();
                params.animating = false;
              }
            });
          }
        });
      });
    },

    _slideElementsOut: function(targetToClear) {
      var params = this.params;

      if (params.slideSum < 2) {
        return;
      }

      if (this._updatePagers("beforePageUpdate") === false) {
        return;
      };

      params.animating = true;
      window.clearTimeout(params.autoId);

      this.element.find(params.itemSelector + " " + params.itemForegroundElementSelector).removeAttr("style");
      this.element.find(params.itemSelector + "." + params.activeItemClass + " " + params.itemForegroundElementSelector).each(function() {
        var pos = params.elementDirection === "fromLeft" ? $(this).data("slidePos") * -1 + params.baseSize - $(this).width() : $(this).data("slidePos") * -1;
        $(this).stop().animate({left: pos}, params.elementSpeed, params.easingType);
      });

      this._moveSlide(targetToClear);
      this._updatePagers("onPageUpdate");
    }
  };

})(jQuery, window, document, undefined);<|endoftext|>


<commit_before>/*
* jQuery loadJSON plugin
* v1.3.2
* https://github.com/kevindb/jquery-load-json
*
* This is a jQuery plugin that enables developers to load JSON data from the server and load JSON object into the DOM.
*
* Copyright 2015 Kevin Morris
* Copyright 2011 Jovan Popovic
* Copyright 2008 Alexandre Caprais
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
*/

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function( root, jQuery ) {
            if ( jQuery === undefined ) {
                // require('jQuery') returns a factory that requires window to build a jQuery instance, we normalize how we use modules
                // that require this pattern but the window provided is a noop if it's defined (how jquery works)
                if ( typeof window !== 'undefined' ) {
                    jQuery = require('jquery');
                }
                else {
                    jQuery = require('jquery')(root);
                }
            }
            factory(jQuery);
            return jQuery;
        };
    } else {
        // Browser globals
        factory(jQuery);
    }

}(function ($) {
	$.fn.loadJSON = function (obj, options) {
		Array.prototype.contains = function(obj) {
		    var i = this.length;
		    while (i--) {
		        if (this[i] == obj) {
		            return true;
		        }
		    }
		    return false;
		}

		function refreshMobileSelect($element) {
			try {
				if ($.isFunction($element.selectmenu)) {
					$element.selectmenu('refresh'); //used in the JQuery mobile
				}

			} catch (ex) { }
		}

		function refreshMobileCheckBox($element) {
			try {
				if ($.isFunction($element.checkboxradio)) {
					$element.checkboxradio('refresh'); //used in the JQuery mobile
				}
			} catch (ex) { }
		}

		function loadSelect(element, aoValues, name) {
			///
			///Load options into the select list
			///
			///<param name="element" type="JQuery:select">Select list</param>
			///<param name="aoValues" type="Array{value,text,selected}">Array of object containin the options</param>
			///<param name="name" type="String">Name of the select list</param>

			var arr = jQuery.makeArray(element);
			var template = $(arr[arr.length - 1]).clone(true);

			//fill started by last
			var objLen = obj.length;
			var i = objLen - 1;

			for (var iCreate=0; iCreate < objLen; ++iCreate) {
				//duplicate the last
				var last = template.clone(true).insertAfter(arr[arr.length - 1]);
				//setElementValue(last, obj[i], name);
				$(last).attr('value', obj[i].value);
				$(last).text(obj[i].text);
				if (obj[i].selected) {
					$(last).attr('selected', true);
				}
				i--;
			}

			///////////////////////////////////////////////////////////////////////////////////////////
			refreshMobileSelect($(element));
			//////////////////////////////////////////////////////////////////////////////////////////
		}

		function setElementValue(element, value, name) {
			var $element = $(element);
			var type = element.type || element.tagName;
			if (type === null) {
				type = element[0].type || element[0].tagName; //select returns undefined if called directly
				if (type === null) {
					return;
				}
			}
			type = type.toLowerCase();
			switch (type) {
				case 'radio':
					if (value.toString().toLowerCase() == element.value.toLowerCase()) {
						$element.prop('checked', true);
					} else {
						$element.prop('checked', false);
					}
					refreshMobileCheckBox($element);
					break;

				case 'checkbox':
					var elementValue = $element.val();

					if ((value.constructor == Array && value.contains(elementValue)) || value == elementValue) {
						$element.prop('checked', true);
					} else {
						$element.prop('checked', false);
					}
					refreshMobileCheckBox($element);
					break;

				case 'option':
					$element.attr('value', value.value);
					$element.text(value.text);
					if (value.selected) {
						$element.attr('selected', true);
					}
					break;

				case 'select-multiple':
					// This is "interesting". In mobile use element.options while in the desktop use element[0].options
					var select = element[0];

					if (element[0].options === null || typeof (element[0].options) == 'undefined') {
						select = element;
					}

					if (select.options.length > 1) {
						// If select list is not empty use values array to select options
						var values = value.constructor == Array ? value : [value];

						// Replaced element with element[0] ???? because now it reports that element.options does not exist
						for (var i = 0; i < select.options.length; i++) {
							for (var j = 0; j < values.length; j++) {
								select.options[i].selected |= select.options[i].value == values[j];
							}
						}

						refreshMobileSelect($element);

					} else {
						// Instead of selecting values use values array to populate select list
						loadSelect(element, value, name);
					}
					break;

				case 'select':
				case 'select-one':
					if (value.constructor == Array) {
						loadSelect(element, value, name);

					} else {
						$element.val(value);
						refreshMobileSelect($element);
					}
					break;

				case 'color':
				case 'date':
				case 'datetime':
				case 'datetime-local':
				case 'email':
				case 'hidden':
				case 'month':
				case 'number':
				case 'password':
				case 'range':
				case 'search':
				case 'tel':
				case 'text':
				case 'time':
				case 'url':
				case 'week':
					$element.val(value);
					break;

				case 'a':
					var href = $element.attr('href');

					if (href) {					// If a href value exists, append value
						var iPosition = href.indexOf('#');

						if (iPosition > 1000000) {
							href = href.substr(0, iPosition) + '&' + name + '=' + value + href.substr(iPosition);

						} else {
							iPosition = href.indexOf('?');

							if (iPosition > 0) {	// If parameters in the URL exists add new pair using &
								href += '&' + name + '=' + value;
							} else {				//otherwise attach pair to URL
								href = href + '?' + name + '=' + value;
							}
						}

					} else {					// If no href exists, set href to value
						href = value;
					}

					$element.attr('href', href);
					break;

				case 'img':

					if (obj.constructor == 'String') {
						//Assumption is that value is in the HREF$ALT format
						var iPosition = value.indexOf('$');
						var src = '';
						var alt = '';

						if (iPosition > 0) {
							src = value.substring(0, iPosition);
							alt = value.substring(iPosition + 1);

						} else {
							src = value;
							var iPositionStart = value.lastIndexOf('/') + 1;
							var iPositionEnd = value.indexOf('.');
							alt = value.substring(iPositionStart, iPositionEnd);
						}

						$element.attr('src', src);
						$element.attr('alt', alt);

					} else {
						$element.attr('src', obj.src);
						$element.attr('alt', obj.alt);
						$element.attr('title', obj.title);
					}
					break;

				case 'textarea':
				case 'submit':
				case 'button':
				default:
					try {
						$element.html(value.toString());
					} catch (exc) { }
			}

		}

		function browseJSON(obj, element, name) {
			var $element = $(element);

			// no object
			if (obj === undefined) {
				// Do nothing

			// branch
			} else if (obj.constructor == Object) {
				if (element.length >= 1 && element[0].tagName == 'OPTION') {
					setElementValue(element[0], obj, name);
				}

				for (var prop in obj) {
					if (prop === null || typeof prop == 'undefined' || prop.length == 0) {
						continue;

					} else {
						//Find an element with class, id, name, or rel attribute that matches the property name
						var child = jQuery.makeArray(jQuery('.' + prop, element)).length > 0 ? jQuery('.' + prop, element) :
													jQuery('#' + prop, element).length > 0 ? jQuery('#' + prop, element) :
													jQuery('[name="' + prop + '"]', element).length > 0 ? jQuery('[name="' + prop + '"]', element) :
													jQuery('[rel="' + prop + '"]');

						if (child.length != 0) {
							browseJSON(obj[prop], jQuery(child, element), prop);
						}
					}
				}

			// array
			} else if (obj.constructor == Array) {
				if (element.length == 1 &&
						(element.type == 'select' || element.type == 'select-one' || element.type == 'select-multiple' ||
						element[0].type == 'select' || element[0].type == 'select-one' || element[0].type == 'select-multiple'
					)) {

					///nova dva reda
					setElementValue(element, obj, name);
					return;

				} else if (element.length > 0 && element[0].type == 'checkbox') {
					element.each(function() {
						setElementValue(this, obj, name);
					});

				} else {
					var arrayElements = $element.children('[rel]');
					if (arrayElements.length > 0) {					//if there are rel=[index] elements populate them instead of iteration
						arrayElements.each(function () {
							var $this = $(this);
							var rel = $this.attr('rel');
							browseJSON(obj[rel], $this, name);
						});

					} else {										//recursive iteration
						var arr = jQuery.makeArray(element);
						var arrLen = arr.length;
						var template = $(arr[arrLen - 1]).clone(true);
						var nbToCreate = obj.length;				//how many duplicate
						var i = 0;

						if (element[0] === null || (element[0] !== null && element[0].tagName != 'OPTION')) {
							for (var iExist=0; iExist < arrLen; ++iExist) {
								if (i < obj.length) {
									var elem = $element.eq(iExist);
									browseJSON(obj[i], elem, name);
								}
								i++;
							}
							nbToCreate = obj.length - arrLen;
						}

						//fill started by last
						i = obj.length - 1;
						for (var iCreate=0; iCreate < nbToCreate; ++iCreate) {
							//duplicate the last
							var last = template.clone(true).insertAfter(arr[arrLen - 1]);
							browseJSON(obj[i], last, name);
							i--;
						}
					}
				}

			// data only
			} else {
				var value = obj;
				var elemLen = element.length;

				if (elemLen > 0) {
					for (var i=0; i < elemLen; ++i) {
						setElementValue(element[i], obj, name);
					}

				} else {
					setElementValue(element, obj, name);
				}
			}
		} //function browseJSON end

		function init(placeholder) {
			var template;

			if (placeholder.data('loadJSON-template') !== null && placeholder.data('loadJSON-template') != '') {
				template = placeholder.data('loadJSON-template');
				placeholder.html(template);
			} else {
				template = placeholder.html();
				placeholder.data('loadJSON-template', template);
			}
		}

		var defaults = {
			onLoading: function () { },
			onLoaded: function () { },
			mobile: false
		};

		properties = $.extend(defaults, options);

		return this.each(function () {
			var $this = $(this);

			if (obj.constructor == String) {
				if (obj.charAt(0) == '{' || obj.charAt(0) == '[') {
					var data = $.parseJSON(obj);
					init($this);
					properties.onLoading();
					browseJSON(data, this);
					properties.onLoaded();
				}
				else {
					var element = $this;
					$.ajax({ url: obj,
						success: function (data) {
							element.loadJSON(data, properties);
						},
						cache: false,
						dataType: 'json'
					});
				}
			}

			else {
				init($this);
				properties.onLoading();
				browseJSON(obj, this);
				properties.onLoaded();
			}
		});
	};
}));
<commit_msg>Minor changes to pass JSHint<commit_after>/*
* jQuery loadJSON plugin
* v1.3.2
* https://github.com/kevindb/jquery-load-json
*
* This is a jQuery plugin that enables developers to load JSON data from the server and load JSON object into the DOM.
*
* Copyright 2015 Kevin Morris
* Copyright 2011 Jovan Popovic
* Copyright 2008 Alexandre Caprais
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
*/

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function( root, jQuery ) {
            if ( jQuery === undefined ) {
                // require('jQuery') returns a factory that requires window to build a jQuery instance, we normalize how we use modules
                // that require this pattern but the window provided is a noop if it's defined (how jquery works)
                if ( typeof window !== 'undefined' ) {
                    jQuery = require('jquery');
                }
                else {
                    jQuery = require('jquery')(root);
                }
            }
            factory(jQuery);
            return jQuery;
        };
    } else {
        // Browser globals
        factory(jQuery);
    }

}(function ($) {
	"use strict";

	$.fn.loadJSON = function (obj, options) {
		Array.prototype.contains = function(obj) {
		    var i = this.length;
		    while (i--) {
		        if (this[i] == obj) {
		            return true;
		        }
		    }
		    return false;
		};

		function refreshMobileSelect($element) {
			try {
				if ($.isFunction($element.selectmenu)) {
					$element.selectmenu('refresh'); //used in the JQuery mobile
				}

			} catch (ex) { }
		}

		function refreshMobileCheckBox($element) {
			try {
				if ($.isFunction($element.checkboxradio)) {
					$element.checkboxradio('refresh'); //used in the JQuery mobile
				}
			} catch (ex) { }
		}

		function loadSelect(element, aoValues, name) {
			///
			///Load options into the select list
			///
			///<param name="element" type="JQuery:select">Select list</param>
			///<param name="aoValues" type="Array{value,text,selected}">Array of object containin the options</param>
			///<param name="name" type="String">Name of the select list</param>

			var arr = jQuery.makeArray(element);
			var template = $(arr[arr.length - 1]).clone(true);

			//fill started by last
			var objLen = obj.length;
			var i = objLen - 1;

			for (var iCreate=0; iCreate < objLen; ++iCreate) {
				//duplicate the last
				var last = template.clone(true).insertAfter(arr[arr.length - 1]);
				//setElementValue(last, obj[i], name);
				$(last).attr('value', obj[i].value);
				$(last).text(obj[i].text);
				if (obj[i].selected) {
					$(last).attr('selected', true);
				}
				i--;
			}

			///////////////////////////////////////////////////////////////////////////////////////////
			refreshMobileSelect($(element));
			//////////////////////////////////////////////////////////////////////////////////////////
		}

		function setElementValue(element, value, name) {
			var $element = $(element);
			var type = element.type || element.tagName;
			if (type === null) {
				type = element[0].type || element[0].tagName; //select returns undefined if called directly
				if (type === null) {
					return;
				}
			}
			type = type.toLowerCase();
			switch (type) {
				case 'radio':
					if (value.toString().toLowerCase() == element.value.toLowerCase()) {
						$element.prop('checked', true);
					} else {
						$element.prop('checked', false);
					}
					refreshMobileCheckBox($element);
					break;

				case 'checkbox':
					var elementValue = $element.val();

					if ((value.constructor == Array && value.contains(elementValue)) || value == elementValue) {
						$element.prop('checked', true);
					} else {
						$element.prop('checked', false);
					}
					refreshMobileCheckBox($element);
					break;

				case 'option':
					$element.attr('value', value.value);
					$element.text(value.text);
					if (value.selected) {
						$element.attr('selected', true);
					}
					break;

				case 'select-multiple':
					// This is "interesting". In mobile use element.options while in the desktop use element[0].options
					var select = element[0];

					if (element[0].options === null || typeof (element[0].options) == 'undefined') {
						select = element;
					}

					if (select.options.length > 1) {
						// If select list is not empty use values array to select options
						var values = value.constructor == Array ? value : [value];

						// Replaced element with element[0] ???? because now it reports that element.options does not exist
						for (var i = 0; i < select.options.length; i++) {
							for (var j = 0; j < values.length; j++) {
								select.options[i].selected |= select.options[i].value == values[j];
							}
						}

						refreshMobileSelect($element);

					} else {
						// Instead of selecting values use values array to populate select list
						loadSelect(element, value, name);
					}
					break;

				case 'select':
				case 'select-one':
					if (value.constructor == Array) {
						loadSelect(element, value, name);

					} else {
						$element.val(value);
						refreshMobileSelect($element);
					}
					break;

				case 'color':
				case 'date':
				case 'datetime':
				case 'datetime-local':
				case 'email':
				case 'hidden':
				case 'month':
				case 'number':
				case 'password':
				case 'range':
				case 'search':
				case 'tel':
				case 'text':
				case 'time':
				case 'url':
				case 'week':
					$element.val(value);
					break;

				case 'a':
					var href = $element.attr('href');

					if (href) {					// If a href value exists, append value
						var iPosition = href.indexOf('#');

						if (iPosition > 1000000) {
							href = href.substr(0, iPosition) + '&' + name + '=' + value + href.substr(iPosition);

						} else {
							iPosition = href.indexOf('?');

							if (iPosition > 0) {	// If parameters in the URL exists add new pair using &
								href += '&' + name + '=' + value;
							} else {				//otherwise attach pair to URL
								href = href + '?' + name + '=' + value;
							}
						}

					} else {					// If no href exists, set href to value
						href = value;
					}

					$element.attr('href', href);
					break;

				case 'img':

					if (obj.constructor == 'String') {
						//Assumption is that value is in the HREF$ALT format
						var iPosition = value.indexOf('$');
						var src = '';
						var alt = '';

						if (iPosition > 0) {
							src = value.substring(0, iPosition);
							alt = value.substring(iPosition + 1);

						} else {
							src = value;
							var iPositionStart = value.lastIndexOf('/') + 1;
							var iPositionEnd = value.indexOf('.');
							alt = value.substring(iPositionStart, iPositionEnd);
						}

						$element.attr('src', src);
						$element.attr('alt', alt);

					} else {
						$element.attr('src', obj.src);
						$element.attr('alt', obj.alt);
						$element.attr('title', obj.title);
					}
					break;

				case 'textarea':
				case 'submit':
				case 'button':
				default:
					try {
						$element.html(value.toString());
					} catch (exc) { }
			}

		}

		function browseJSON(obj, element, name) {
			var $element = $(element);

			// no object
			if (obj === undefined) {
				// Do nothing

			// branch
			} else if (obj.constructor == Object) {
				if (element.length >= 1 && element[0].tagName == 'OPTION') {
					setElementValue(element[0], obj, name);
				}

				for (var prop in obj) {
					if (prop === null || typeof prop == 'undefined' || prop.length === 0) {
						continue;

					} else {
						//Find an element with class, id, name, or rel attribute that matches the property name
						var child = jQuery.makeArray(jQuery('.' + prop, element)).length > 0 ? jQuery('.' + prop, element) :
													jQuery('#' + prop, element).length > 0 ? jQuery('#' + prop, element) :
													jQuery('[name="' + prop + '"]', element).length > 0 ? jQuery('[name="' + prop + '"]', element) :
													jQuery('[rel="' + prop + '"]');

						if (child.length !== 0) {
							browseJSON(obj[prop], jQuery(child, element), prop);
						}
					}
				}

			// array
			} else if (obj.constructor == Array) {
				if (element.length == 1 &&
						(element.type == 'select' || element.type == 'select-one' || element.type == 'select-multiple' ||
						element[0].type == 'select' || element[0].type == 'select-one' || element[0].type == 'select-multiple'
					)) {

					///nova dva reda
					setElementValue(element, obj, name);
					return;

				} else if (element.length > 0 && element[0].type == 'checkbox') {
					element.each(function() {
						setElementValue(this, obj, name);
					});

				} else {
					var arrayElements = $element.children('[rel]');
					if (arrayElements.length > 0) {					//if there are rel=[index] elements populate them instead of iteration
						arrayElements.each(function () {
							var $this = $(this);
							var rel = $this.attr('rel');
							browseJSON(obj[rel], $this, name);
						});

					} else {										//recursive iteration
						var arr = jQuery.makeArray(element);
						var arrLen = arr.length;
						var template = $(arr[arrLen - 1]).clone(true);
						var nbToCreate = obj.length;				//how many duplicate
						var i = 0;

						if (element[0] === null || (element[0] !== null && element[0].tagName != 'OPTION')) {
							for (var iExist=0; iExist < arrLen; ++iExist) {
								if (i < obj.length) {
									var elem = $element.eq(iExist);
									browseJSON(obj[i], elem, name);
								}
								i++;
							}
							nbToCreate = obj.length - arrLen;
						}

						//fill started by last
						i = obj.length - 1;
						for (var iCreate=0; iCreate < nbToCreate; ++iCreate) {
							//duplicate the last
							var last = template.clone(true).insertAfter(arr[arrLen - 1]);
							browseJSON(obj[i], last, name);
							i--;
						}
					}
				}

			// data only
			} else {
				var elemLen = element.length;

				if (elemLen > 0) {
					for (var i=0; i < elemLen; ++i) {
						setElementValue(element[i], obj, name);
					}

				} else {
					setElementValue(element, obj, name);
				}
			}
		} //function browseJSON end

		function init(placeholder) {
			var template;

			if (placeholder.data('loadJSON-template') !== null && placeholder.data('loadJSON-template') != '') {
				template = placeholder.data('loadJSON-template');
				placeholder.html(template);
			} else {
				template = placeholder.html();
				placeholder.data('loadJSON-template', template);
			}
		}

		var defaults = {
			onLoading: function () { },
			onLoaded: function () { },
			mobile: false
		};

		var properties = $.extend(defaults, options);

		return this.each(function () {
			var $this = $(this);

			if (obj.constructor == String) {
				if (obj.charAt(0) == '{' || obj.charAt(0) == '[') {
					var data = $.parseJSON(obj);
					init($this);
					properties.onLoading();
					browseJSON(data, this);
					properties.onLoaded();
				}
				else {
					var element = $this;
					$.ajax({ url: obj,
						success: function (data) {
							element.loadJSON(data, properties);
						},
						cache: false,
						dataType: 'json'
					});
				}
			}

			else {
				init($this);
				properties.onLoading();
				browseJSON(obj, this);
				properties.onLoaded();
			}
		});
	};
}));
<|endoftext|>


<commit_before>/*!
 * ImageUploader (for jQuery)
 * Version 0.3.4 (26/01/2015)
 * Copyright 2012-* Julien Deniau <julien.deniau@gmail.com>
 * Licensed under MIT (https://github.com/jdeniau/jquery-image-uploader/LICENSE.md)
 */

if(typeof jQuery !== undefined){
    (function($){
        // init
        var ImageUploader = function (params) {
            this.init(params);
            this.main();
        }

        // default settings
        ImageUploader.defaults = {
            fileField: null,
            urlField: null,
            urlFieldSubmit: null,

            hideFileField: true,
            hideUrlField: true,

            url: null,

            thumbnails: {
                div: null,
                width: null,
                height: null
            },

            maxFileSize: 0,
            allowDuplicate: false,
            //progressBar: null,

            thumbnailReady: $.noop,

            onFileAdded: function(file) { return false; },
            onFilesSelected: function() { return false; },
            onUrlSelected: function() { return false; },
            onDragStart: function(event) { return false; },
            onDragEnd: function(event) { return false; },
            onDragEnter: function(event) { return false; },
            onDragLeave: function(event) { return false; },
            onDragOver: function(event) { return false; },
            onDrop: function(event) { return false; },
            onUploadProgress: function(event) { return false; },
            beforeUpload: function() { return true; },
            afterUpload: function() { return false; },
            error: function(msg) { alert(msg); }
        }

        ImageUploader.prototype = {
            // Init
            init: function (params) {
                instance = this;
                this.options = $.extend({}, ImageUploader.defaults, params);

                this.canUpload = true;
                this.uploadFileList = new Array();
                this.allUploadedFileList = new Array();
                this.currentThumbnail = null;
            },

            /**
             * fileApiSupported check if the file api is supported
             *
             * @return void
             */
            fileApiSupported: function() {
                return (window.File && window.FileReader && window.FileList && window.FormData);
            },

            /**
             * onDragLeave
             *
             * @param event $event
             * @return void
             */
            onDragLeave: function(event) {
                if ($(event.target)[0] === instance.options.dropZone[0]) {
                    //you can remove a style from the drop zone
                    return instance.options.onDragLeave(event);
                }
            },

            /**
             * onDragEnter
             *
             * @param {Event} event
             * @return void
             */
            onDragEnter: function (event) {
                if ($(event.target)[0] === instance.options.dropZone[0]) {
                    //you can add a style to the drop zone
                    return instance.options.onDragEnter(event);
                }
            },

            /**
             * onDragStart
             *
             * @param {Event} event
             * @return void
             */
            onDragStart: function (event) {
                event.preventDefault();
                event.stopPropagation();
                return instance.options.onDragStart(event);
            },

            /**
             * onDragEnd
             *
             * @param {Event} event
             * @return void
             */
            onDragEnd: function (event) {
                event.preventDefault();
                event.stopPropagation();
                return instance.options.onDragEnd(event);
            },

            /**
             * onDragOver
             *
             * @param event $event
             * @return void
             */
            onDragOver: function (event) {
                event.preventDefault();
                event.stopPropagation();
                //event.originalEvent.dataTransfer.effectAllowed= "copy";
                //event.originalEvent.dataTransfer.dropEffect = "copy";

                return instance.options.onDragOver(event);
            },

            /**
             * onDrop
             *
             * @param event $event
             * @return void
             */
            onDrop: function (event) {
                event.preventDefault();
                event.stopPropagation();
                instance.addFiles(event.originalEvent.dataTransfer.files);

                return instance.options.onDrop(event);
            },

            uploadStarted: function (event) {
                if (instance.options.thumbnails) {
                    instance.currentThumbnail = instance.options.thumbnails.div.find('[data-upload-status="waiting"]:first');
                    instance.currentThumbnail.attr('data-upload-status', 'uploading');
                    instance.currentThumbnail.append($('
').append($('
')));
                }
            },

            /**
             * onUploadProgress
             *
             * @param event $event
             * @return void
             */
            onUploadProgress: function (event) {
                if (event.lengthComputable) {
                    if (!instance.currentThumbnail || instance.currentThumbnail.length == 0) {
                        instance.uploadStarted();
                        //instance.currentThumbnail = instance.options.thumbnails.div.find('[data-upload-status="uploading"]:first');
                    }

                    if (instance.currentThumbnail) {
                        instance.currentThumbnail.find('.progress > div').width(event.loaded * 100 / event.total + '%');
                    }
                }

                return instance.options.onUploadProgress(event);
            },

            /**
             * uploadComplete
             *
             * @return void
             */
            uploadComplete: function (event) {
                xhr = event.currentTarget;
                instance.canUpload = true;

                if (xhr.status == 200) {
                    var thumbnailToReturn = null;
                    if (instance.currentThumbnail) {
                        instance.currentThumbnail.find('.progress > div').width('100%');
                        thumbnailToReturn = instance.currentThumbnail;
                        instance.currentThumbnail = null;
                    }
                    instance.options.afterUpload(event.target.response, thumbnailToReturn);
                    instance.uploadNextFile();
                } else {
                    instance.uploadFailed();
                }
            },

            /**
             * uploadFailed
             *
             * @return void
             */
            uploadFailed: function () {
                this.canUpload = true;
                if (this.currentThumbnail) {
                    this.currentThumbnail.remove();
                }
                this.currentThumbnail = null;
                this.options.error('upload failed');
                this.uploadNextFile();
            },

            /**
             * uploadCanceled
             *
             * @return void
             */
            uploadCanceled: function () {
                this.canUpload = true;
                this.currentThumbnail = null;
                this.options.error('upload canceled');
                this.uploadNextFile();
            },

            /**
             * addUploadFile
             *
             * @param file $file
             * @access public
             * @return void
             */
            addUploadFile: function (file) {
                this.allUploadedFileList.push(file);
                this.uploadFileList.push(file);
                this.uploadNextFile();
            },

            /**
             * fileAlreadyUploaded
             *
             * @param file $file
             * @access public
             * @return boolean
             */
            fileAlreadyUploaded: function (file) {
                for (i in this.allUploadedFileList) {
                    f = this.allUploadedFileList[i];
                    if (file.name == f.name && file.size == f.size && file.type == f.type) {
                        return true;
                    }
                }
                return false;
            },

            /**
             * uploadNextFile
             *
             * @access public
             * @return void
             */
            uploadNextFile: function () {
                if (this.canUpload && this.uploadFileList.length > 0) {
                    file = this.uploadFileList.shift();
                    this.canUpload = false;
                    this.uploadFile(file);
                }
            },

            /**
             * uploadFile upload the file
             *
             * @param file $file
             * @return void
             */
            uploadFile: function (file) {
                xhr = new XMLHttpRequest();
                if (xhr.upload && this.options.beforeUpload()) {
                    xhr.open("POST", this.options.url);

                    if (file instanceof File) {
                        var fd = new FormData();
                        fd.append('file', file);
                    } else {
                        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                        var fd = 'url=' + encodeURIComponent(file.name);
                    }

                    /* event listners */
                    xhr.upload.addEventListener('progress',  this.onUploadProgress, false);
                    xhr.addEventListener("loadstart", this.uploadStarted, false);
                    xhr.addEventListener("load", this.uploadComplete, false);
                    xhr.addEventListener("error", this.uploadFailed, false);
                    xhr.addEventListener("abort", this.uploadCanceled, false);

                    //xhr.setRequestHeader("Content-Type", "multipart/form-data");
                    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                    //xhr.setRequestHeader("X-File-Name", file.name);
                    //xhr.setRequestHeader("X-File-Size", file.size);
                    //xhr.setRequestHeader("X-File-Type", file.type);

                    xhr.send(fd);
                }
            },

            /**
             * onFilesSelected
             *
             * @param event $event
             * @return void
             */
            onFilesSelected: function (event) {
                event.preventDefault();
                event.stopPropagation();
                instance.addFiles(event.target.files);
                $(this).val('');

                return instance.options.onFilesSelected();
            },

            /**
             * onUrlSelected
             *
             * @param event $event
             * @return void
             */
            onUrlSelected: function (event) {
                var url = instance.options.urlField.val();
                if (url) {
                    instance.addFileByUrl(url);
                }

                return instance.options.onUrlSelected();
            },

            /**
             * add a file by Url
             */
            addFileByUrl: function (url) {
                return this.addFile({ name: url });
            },

            /**
             * addFile add a single file to the file list
             */
            addFile: function (file) {
                return this.addFiles([file]);
            },

            /**
             * addFiles add files to the file list
             *
             * @param files $files
             * @return void
             */
            addFiles: function (files) {
                if (this.fileApiSupported()) {
                    var reader = null;

                    for (var i=0; i < files.length; i++) {
                        if (this.options.maxFileSize > 0 && file.size > this.options.maxFileSize) {
                            return this.options.error('the file you are trying to upload is too big');
                        } else if (!this.options.allowDuplicate && this.fileAlreadyUploaded(files[i])) {
                            return this.options.error('the file you are trying to upload has already been sent');
                        } else {
                            this.options.onFileAdded(files[i]);

                            if (this.options.thumbnails || this.options.thumbnailReady != $.noop) {
                                if (files[i] instanceof File) {
                                    this.options.thumbnails.div.file = files[i];
                                    reader = new FileReader();
                                    reader.onload = function (evt) {
                                        instance.displayImage(evt.target.result);
                                     };
                                    reader.readAsDataURL(files[i]);
                                } else {
                                    this.displayImage(files[i].name);
                                }
                            }

                            try {
                                this.addUploadFile(files[i]);
                            } catch (e) {
                                this.uploadFailed();
                            }
                        }
                    }
               } else {
                   alert('files api not supported');
               }
            },

            displayImage: function (src) {
                var thumb = new Image();
                thumb.src = src;
                $(thumb).hide();
                var thumbContainer = $('
')
                    .attr('data-upload-status', 'waiting')
                    .css({'overflow': 'hidden', 'position': 'relative'})
                    .append(thumb);

                thumb.onload = function() {
                    var otw = instance.options.thumbnails.width;
                    var oth = instance.options.thumbnails.height;
                    var ratio = thumb.width / thumb.height;

                    if (instance.options.thumbnails.crop && otw > 0 && oth > 0) {
                        thumbContainer.width(otw);
                        thumbContainer.height(oth);
                        $(thumb).css('position', 'absolute');
                        var wantedRatio = otw / oth;

                        if (wantedRatio > ratio) {
                            // portrait image
                            if (instance.options.thumbnails.crop == 'zoom') {
                                thumb.width = otw;
                                thumb.height = otw / ratio;
                                $(thumb).css('top', '-' + parseInt((thumb.height - oth) / 2) + 'px');
                            } else {
                                thumb.width = oth * ratio;
                                thumb.height = oth;
                                $(thumb).css('left', parseInt((otw - thumb.width) / 2) + 'px');
                            }
                        } else {
                            if (instance.options.thumbnails.crop == 'zoom') {
                                thumb.height = oth;
                                thumb.width = oth * ratio;
                                $(thumb).css('left', '-' + parseInt((thumb.width - otw) / 2) + 'px');
                            } else {
                                thumb.width = otw;
                                thumb.height = oth / ratio;
                                $(thumb).css('top', parseInt((oth - thumb.height) / 2) + 'px');
                            }
                        }
                    } else {
                        if (otw > 0) {
                            thumb.width = otw;
                        } else if (oth > 0) {
                            thumb.width = oth * ratio;
                        }

                        if (oth > 0) {
                            thumb.height = oth;
                        } else if (otw > 0) {
                            thumb.height = otw / ratio;
                        }
                    }
                    $(thumb).css({ width: thumb.width, height : thumb.height });

                    $(thumb).show('slow');
                }

                if (instance.options.thumbnailReady != $.noop) {
                    instance.options.thumbnailReady(thumbContainer);
                } else {
                    instance.options.thumbnails.div.append(thumbContainer);
                }
            },

            /**
             * prepare thumbnails div
             *
             * @return void
             */
            prepareThumbnails: function () {
                if (this.options.thumbnails) {
                    if (typeof this.options.thumbnails != 'object') {
                        var tmpDiv = null;
                        if (typeof this.options.thumbnails == 'string') {
                            tmpDiv = $(this.options.thumbnails);
                        }
                        this.options.thumbnails = { div: tmpDiv, width: null, height: null };
                    }

                    if (typeof this.options.thumbnails.div == 'string') {
                        this.options.thumbnails.div = $(this.options.thumbnails.div);
                    }

                    if (typeof this.options.thumbnails == 'object' && this.options.thumbnails.div == undefined) {
                        this.options.thumbnails.div = null;
                    }

                    if (this.options.thumbnails.div == null) {
                        this.options.thumbnails.div = $('
');
                        this.options.dropZone.after(this.options.thumbnails.div);
                    }
                }
            },

            main: function() {
                // ===============================
                // main process
                // ===============================
                var othis = this;

                // Dropzone management
                if (this.options.dropZone != null) {
                    this.options.dropZone.on('dragstart', this.onDragStart);
                    this.options.dropZone.on('dragend', this.onDragEnd);
                    this.options.dropZone.on('dragleave', this.onDragLeave);
                    this.options.dropZone.on('dragenter', this.onDragEnter);
                    this.options.dropZone.on('dragover', this.onDragOver);
                    this.options.dropZone.on('drop', this.onDrop);
                }

                if (this.options.fileField != null) {
                    // open fileField on click on the dropZone
                    if (typeof this.options.fileField == 'string') {
                        this.options.fileField = $(this.options.fileField);
                    }
                    this.options.dropZone.on('click', function() {
                        othis.options.fileField.trigger('click');
                    });

                    this.options.fileField.on('change', this.onFilesSelected);
                    if (this.options.hideFileField == true) {
                        this.hide(this.options.fileField);
                    }
                }

                if (this.options.urlField != null) {
                    if (typeof this.options.urlField == 'string') {
                        this.options.urlField = $(this.options.urlField);
                    }

                    if (this.options.urlFieldSubmit !== null) {
                        if (typeof this.options.urlFieldSubmit == 'string') {
                            this.options.urlFieldSubmit = $(this.options.urlFieldSubmit);
                        }
                        this.options.urlFieldSubmit.on('click', this.onUrlSelected);
                    } else {
                        this.options.urlField.on('change', this.onUrlSelected);
                    }

                    if (this.options.hideUrlField == true) {
                        this.hide(this.options.urlField);
                    }
                }

                // preparing thumbnails div
                this.prepareThumbnails();

                return this;
            },

            /**
             * Hide a jquery element. Use size=0x0 instead of native jquery hide()
             * to avoid safari bugs
             *
             * @return void
             */
            hide: function($element) {
                $element.css({
                    'width': '0px',
                    'height': '0px',
                    'padding': '0px',
                    'margin': '0px',
                    'border': 'none'
                });
            }
        };

        $.fn.imageUploader = function(params) {
            params = $.extend({ dropZone: $(this) }, params);
            var instance = new ImageUploader(params);

            $(this).data('imageUploader', instance);

            return this;
        };

    })(jQuery);
}
<commit_msg>bind callbacks to the class instance<commit_after>/*!
 * ImageUploader (for jQuery)
 * Version 0.3.4 (26/01/2015)
 * Copyright 2012-* Julien Deniau <julien.deniau@gmail.com>
 * Licensed under MIT (https://github.com/jdeniau/jquery-image-uploader/LICENSE.md)
 */

if(typeof jQuery !== undefined){
    (function($){
        // init
        var ImageUploader = function (params) {
            this.init(params);
            this.main();
        }

        // default settings
        ImageUploader.defaults = {
            fileField: null,
            urlField: null,
            urlFieldSubmit: null,

            hideFileField: true,
            hideUrlField: true,

            url: null,

            thumbnails: {
                div: null,
                width: null,
                height: null
            },

            maxFileSize: 0,
            allowDuplicate: false,
            //progressBar: null,

            thumbnailReady: $.noop,

            onFileAdded: function(file) { return false; },
            onFilesSelected: function() { return false; },
            onUrlSelected: function() { return false; },
            onDragStart: function(event) { return false; },
            onDragEnd: function(event) { return false; },
            onDragEnter: function(event) { return false; },
            onDragLeave: function(event) { return false; },
            onDragOver: function(event) { return false; },
            onDrop: function(event) { return false; },
            onUploadProgress: function(event) { return false; },
            beforeUpload: function() { return true; },
            afterUpload: function() { return false; },
            error: function(msg) { alert(msg); }
        }

        ImageUploader.prototype = {
            // Init
            init: function (params) {
                instance = this;
                this.options = $.extend({}, ImageUploader.defaults, params);

                this.canUpload = true;
                this.uploadFileList = new Array();
                this.allUploadedFileList = new Array();
                this.currentThumbnail = null;
            },

            /**
             * fileApiSupported check if the file api is supported
             *
             * @return void
             */
            fileApiSupported: function() {
                return (window.File && window.FileReader && window.FileList && window.FormData);
            },

            /**
             * onDragLeave
             *
             * @param event $event
             * @return void
             */
            onDragLeave: function(event) {
                if ($(event.target)[0] === instance.options.dropZone[0]) {
                    //you can remove a style from the drop zone
                    return instance.options.onDragLeave(event);
                }
            },

            /**
             * onDragEnter
             *
             * @param {Event} event
             * @return void
             */
            onDragEnter: function (event) {
                if ($(event.target)[0] === instance.options.dropZone[0]) {
                    //you can add a style to the drop zone
                    return instance.options.onDragEnter(event);
                }
            },

            /**
             * onDragStart
             *
             * @param {Event} event
             * @return void
             */
            onDragStart: function (event) {
                event.preventDefault();
                event.stopPropagation();
                return instance.options.onDragStart(event);
            },

            /**
             * onDragEnd
             *
             * @param {Event} event
             * @return void
             */
            onDragEnd: function (event) {
                event.preventDefault();
                event.stopPropagation();
                return instance.options.onDragEnd(event);
            },

            /**
             * onDragOver
             *
             * @param event $event
             * @return void
             */
            onDragOver: function (event) {
                event.preventDefault();
                event.stopPropagation();
                //event.originalEvent.dataTransfer.effectAllowed= "copy";
                //event.originalEvent.dataTransfer.dropEffect = "copy";

                return instance.options.onDragOver(event);
            },

            /**
             * onDrop
             *
             * @param event $event
             * @return void
             */
            onDrop: function (event) {
                event.preventDefault();
                event.stopPropagation();
                instance.addFiles(event.originalEvent.dataTransfer.files);

                return instance.options.onDrop(event);
            },

            uploadStarted: function (event) {
                if (instance.options.thumbnails) {
                    instance.currentThumbnail = instance.options.thumbnails.div.find('[data-upload-status="waiting"]:first');
                    instance.currentThumbnail.attr('data-upload-status', 'uploading');
                    instance.currentThumbnail.append($('
').append($('
')));
                }
            },

            /**
             * onUploadProgress
             *
             * @param event $event
             * @return void
             */
            onUploadProgress: function (event) {
                if (event.lengthComputable) {
                    if (!instance.currentThumbnail || instance.currentThumbnail.length == 0) {
                        instance.uploadStarted();
                        //instance.currentThumbnail = instance.options.thumbnails.div.find('[data-upload-status="uploading"]:first');
                    }

                    if (instance.currentThumbnail) {
                        instance.currentThumbnail.find('.progress > div').width(event.loaded * 100 / event.total + '%');
                    }
                }

                return instance.options.onUploadProgress(event);
            },

            /**
             * uploadComplete
             *
             * @return void
             */
            uploadComplete: function (event) {
                xhr = event.currentTarget;
                instance.canUpload = true;

                if (xhr.status == 200) {
                    var thumbnailToReturn = null;
                    if (instance.currentThumbnail) {
                        instance.currentThumbnail.find('.progress > div').width('100%');
                        thumbnailToReturn = instance.currentThumbnail;
                        instance.currentThumbnail = null;
                    }
                    instance.options.afterUpload(event.target.response, thumbnailToReturn);
                    instance.uploadNextFile();
                } else {
                    instance.uploadFailed();
                }
            },

            /**
             * uploadFailed
             *
             * @return void
             */
            uploadFailed: function () {
                this.canUpload = true;
                if (this.currentThumbnail) {
                    this.currentThumbnail.remove();
                }
                this.currentThumbnail = null;
                this.options.error('upload failed');
                this.uploadNextFile();
            },

            /**
             * uploadCanceled
             *
             * @return void
             */
            uploadCanceled: function () {
                this.canUpload = true;
                this.currentThumbnail = null;
                this.options.error('upload canceled');
                this.uploadNextFile();
            },

            /**
             * addUploadFile
             *
             * @param file $file
             * @access public
             * @return void
             */
            addUploadFile: function (file) {
                this.allUploadedFileList.push(file);
                this.uploadFileList.push(file);
                this.uploadNextFile();
            },

            /**
             * fileAlreadyUploaded
             *
             * @param file $file
             * @access public
             * @return boolean
             */
            fileAlreadyUploaded: function (file) {
                for (i in this.allUploadedFileList) {
                    f = this.allUploadedFileList[i];
                    if (file.name == f.name && file.size == f.size && file.type == f.type) {
                        return true;
                    }
                }
                return false;
            },

            /**
             * uploadNextFile
             *
             * @access public
             * @return void
             */
            uploadNextFile: function () {
                if (this.canUpload && this.uploadFileList.length > 0) {
                    file = this.uploadFileList.shift();
                    this.canUpload = false;
                    this.uploadFile(file);
                }
            },

            /**
             * uploadFile upload the file
             *
             * @param file $file
             * @return void
             */
            uploadFile: function (file) {
                xhr = new XMLHttpRequest();
                if (xhr.upload && this.options.beforeUpload()) {
                    xhr.open("POST", this.options.url);

                    if (file instanceof File) {
                        var fd = new FormData();
                        fd.append('file', file);
                    } else {
                        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                        var fd = 'url=' + encodeURIComponent(file.name);
                    }

                    /* event listners */
                    xhr.upload.addEventListener('progress',  this.onUploadProgress.bind(this), false);
                    xhr.addEventListener("loadstart", this.uploadStarted.bind(this), false);
                    xhr.addEventListener("load", this.uploadComplete.bind(this), false);
                    xhr.addEventListener("error", this.uploadFailed.bind(this), false);
                    xhr.addEventListener("abort", this.uploadCanceled.bind(this), false);

                    //xhr.setRequestHeader("Content-Type", "multipart/form-data");
                    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                    //xhr.setRequestHeader("X-File-Name", file.name);
                    //xhr.setRequestHeader("X-File-Size", file.size);
                    //xhr.setRequestHeader("X-File-Type", file.type);

                    xhr.send(fd);
                }
            },

            /**
             * onFilesSelected
             *
             * @param event $event
             * @return void
             */
            onFilesSelected: function (event) {
                event.preventDefault();
                event.stopPropagation();
                instance.addFiles(event.target.files);
                $(this).val('');

                return instance.options.onFilesSelected();
            },

            /**
             * onUrlSelected
             *
             * @param event $event
             * @return void
             */
            onUrlSelected: function (event) {
                var url = instance.options.urlField.val();
                if (url) {
                    instance.addFileByUrl(url);
                }

                return instance.options.onUrlSelected();
            },

            /**
             * add a file by Url
             */
            addFileByUrl: function (url) {
                return this.addFile({ name: url });
            },

            /**
             * addFile add a single file to the file list
             */
            addFile: function (file) {
                return this.addFiles([file]);
            },

            /**
             * addFiles add files to the file list
             *
             * @param files $files
             * @return void
             */
            addFiles: function (files) {
                if (this.fileApiSupported()) {
                    var reader = null;

                    for (var i=0; i < files.length; i++) {
                        if (this.options.maxFileSize > 0 && file.size > this.options.maxFileSize) {
                            return this.options.error('the file you are trying to upload is too big');
                        } else if (!this.options.allowDuplicate && this.fileAlreadyUploaded(files[i])) {
                            return this.options.error('the file you are trying to upload has already been sent');
                        } else {
                            this.options.onFileAdded(files[i]);

                            if (this.options.thumbnails || this.options.thumbnailReady != $.noop) {
                                if (files[i] instanceof File) {
                                    this.options.thumbnails.div.file = files[i];
                                    reader = new FileReader();
                                    reader.onload = function (evt) {
                                        instance.displayImage(evt.target.result);
                                     };
                                    reader.readAsDataURL(files[i]);
                                } else {
                                    this.displayImage(files[i].name);
                                }
                            }

                            try {
                                this.addUploadFile(files[i]);
                            } catch (e) {
                                this.uploadFailed();
                            }
                        }
                    }
               } else {
                   alert('files api not supported');
               }
            },

            displayImage: function (src) {
                var thumb = new Image();
                thumb.src = src;
                $(thumb).hide();
                var thumbContainer = $('
')
                    .attr('data-upload-status', 'waiting')
                    .css({'overflow': 'hidden', 'position': 'relative'})
                    .append(thumb);

                thumb.onload = function() {
                    var otw = instance.options.thumbnails.width;
                    var oth = instance.options.thumbnails.height;
                    var ratio = thumb.width / thumb.height;

                    if (instance.options.thumbnails.crop && otw > 0 && oth > 0) {
                        thumbContainer.width(otw);
                        thumbContainer.height(oth);
                        $(thumb).css('position', 'absolute');
                        var wantedRatio = otw / oth;

                        if (wantedRatio > ratio) {
                            // portrait image
                            if (instance.options.thumbnails.crop == 'zoom') {
                                thumb.width = otw;
                                thumb.height = otw / ratio;
                                $(thumb).css('top', '-' + parseInt((thumb.height - oth) / 2) + 'px');
                            } else {
                                thumb.width = oth * ratio;
                                thumb.height = oth;
                                $(thumb).css('left', parseInt((otw - thumb.width) / 2) + 'px');
                            }
                        } else {
                            if (instance.options.thumbnails.crop == 'zoom') {
                                thumb.height = oth;
                                thumb.width = oth * ratio;
                                $(thumb).css('left', '-' + parseInt((thumb.width - otw) / 2) + 'px');
                            } else {
                                thumb.width = otw;
                                thumb.height = oth / ratio;
                                $(thumb).css('top', parseInt((oth - thumb.height) / 2) + 'px');
                            }
                        }
                    } else {
                        if (otw > 0) {
                            thumb.width = otw;
                        } else if (oth > 0) {
                            thumb.width = oth * ratio;
                        }

                        if (oth > 0) {
                            thumb.height = oth;
                        } else if (otw > 0) {
                            thumb.height = otw / ratio;
                        }
                    }
                    $(thumb).css({ width: thumb.width, height : thumb.height });

                    $(thumb).show('slow');
                }

                if (instance.options.thumbnailReady != $.noop) {
                    instance.options.thumbnailReady(thumbContainer);
                } else {
                    instance.options.thumbnails.div.append(thumbContainer);
                }
            },

            /**
             * prepare thumbnails div
             *
             * @return void
             */
            prepareThumbnails: function () {
                if (this.options.thumbnails) {
                    if (typeof this.options.thumbnails != 'object') {
                        var tmpDiv = null;
                        if (typeof this.options.thumbnails == 'string') {
                            tmpDiv = $(this.options.thumbnails);
                        }
                        this.options.thumbnails = { div: tmpDiv, width: null, height: null };
                    }

                    if (typeof this.options.thumbnails.div == 'string') {
                        this.options.thumbnails.div = $(this.options.thumbnails.div);
                    }

                    if (typeof this.options.thumbnails == 'object' && this.options.thumbnails.div == undefined) {
                        this.options.thumbnails.div = null;
                    }

                    if (this.options.thumbnails.div == null) {
                        this.options.thumbnails.div = $('
');
                        this.options.dropZone.after(this.options.thumbnails.div);
                    }
                }
            },

            main: function() {
                // ===============================
                // main process
                // ===============================
                var othis = this;

                // Dropzone management
                if (this.options.dropZone != null) {
                    this.options.dropZone.on('dragstart', this.onDragStart);
                    this.options.dropZone.on('dragend', this.onDragEnd);
                    this.options.dropZone.on('dragleave', this.onDragLeave);
                    this.options.dropZone.on('dragenter', this.onDragEnter);
                    this.options.dropZone.on('dragover', this.onDragOver);
                    this.options.dropZone.on('drop', this.onDrop);
                }

                if (this.options.fileField != null) {
                    // open fileField on click on the dropZone
                    if (typeof this.options.fileField == 'string') {
                        this.options.fileField = $(this.options.fileField);
                    }
                    this.options.dropZone.on('click', function() {
                        othis.options.fileField.trigger('click');
                    });

                    this.options.fileField.on('change', this.onFilesSelected);
                    if (this.options.hideFileField == true) {
                        this.hide(this.options.fileField);
                    }
                }

                if (this.options.urlField != null) {
                    if (typeof this.options.urlField == 'string') {
                        this.options.urlField = $(this.options.urlField);
                    }

                    if (this.options.urlFieldSubmit !== null) {
                        if (typeof this.options.urlFieldSubmit == 'string') {
                            this.options.urlFieldSubmit = $(this.options.urlFieldSubmit);
                        }
                        this.options.urlFieldSubmit.on('click', this.onUrlSelected);
                    } else {
                        this.options.urlField.on('change', this.onUrlSelected);
                    }

                    if (this.options.hideUrlField == true) {
                        this.hide(this.options.urlField);
                    }
                }

                // preparing thumbnails div
                this.prepareThumbnails();

                return this;
            },

            /**
             * Hide a jquery element. Use size=0x0 instead of native jquery hide()
             * to avoid safari bugs
             *
             * @return void
             */
            hide: function($element) {
                $element.css({
                    'width': '0px',
                    'height': '0px',
                    'padding': '0px',
                    'margin': '0px',
                    'border': 'none'
                });
            }
        };

        $.fn.imageUploader = function(params) {
            params = $.extend({ dropZone: $(this) }, params);
            var instance = new ImageUploader(params);

            $(this).data('imageUploader', instance);

            return this;
        };

    })(jQuery);
}
<|endoftext|>