(function($) {

  $.fn.fly = function(options) {

    var options = $.extend({}, $.fn.fly.defaults, options);

    //loop through the items
    this.each(function() {
      var $this = $(this);

      var direction = options.direction;
      var duration = options.duration;
      var max_height = options.height;

      var plane = $this.width(); //width of plane

      var operator = "-";
      if (direction != "left") {
        operator = "+";
      }

      var rand_height = function() {
        return Math.floor(Math.random() * max_height);
      }

      var zoom = function(start_y) {
        //recalculate the browser width
        var width = $(window).width();
        //starting x cordinate for the plane
        var start_x = width;
        //browser width plus the width of the plane
        var end_x = width + plane;

        if (direction != "left") {
          start_x = 0 - plane;
        }

        //get the ending y coordinate
        var end_y = rand_height();

        $this.css({"top": start_y, "left": start_x});
        $this.animate({"top": end_y, "left": operator+"="+end_x+"px"}, duration, "linear", function() {
          zoom(end_y);
        });
      }

      //browser width
      var width = $(window).width();
      //browser width plus the width of the plane
      var width_t = width + plane;
      //calculate the random location that the plane will start
      var rand = Math.floor(Math.random() * width);

      //ending random y coordinate
      var rand_y = rand + plane;
      if (direction != "left") {
        rand_y = width - rand;
      }
      //new random y coordinate
      var rand_x = rand_height();

      $this.css({"top": rand_x, "left": rand});
      $this.animate({"top": rand_x, "left": operator+"="+rand_y+"px"}, duration, "linear", function() {
        zoom(rand_x);
      });

    //end $.each loop
    });

    // returns the jQuery object to allow for chainability.
    return this;
  }

  //Plugin Defaults
  $.fn.fly.defaults = {
    direction: "left",
    duration: 50000,
    height: 145
  }

})(jQuery);
