﻿/*
* author: IP
* notes: 
*/

jQuery.fn.fsPreviewBox = function(options) {
  var defaults = {
    animate: true,
    offset: 5
  };

  var settings = $.extend({}, defaults, options);
  var mouseover

  return this.each(function(i) {

    var $this = $(this);
    $this.data("myIndex", i);

    $this.hover(
      function() {
        $("#preview-box").remove();
        mouseover = $this.data("myIndex")
        createPreviewBox($this)
      },
      function() {
        $("#preview-box").remove();
        mouseover = -1
      }
    );

  });

  function createPreviewBox($this) {
    var $href = $this.find('a').attr('href');
    $href = $href.split("?");
    $href = "previewContent.php?" + $href[1];

    var $container = $(document.createElement("div"));
    $container.attr("id", "preview-box");
    $container.hide();

    $container.load($href, function() { //consume the content
      if (mouseover == $this.data("myIndex")) {
        $("body").append($container);
        positionPreviewBox($this, $container)
      } else {
        $container.remove()
      }
    });
  }

  function positionPreviewBox($this, $container) {
    var $position = $this.offset()
    var $distToBottom = ($(window).height() - ($position.top - $(window).scrollTop()))
    var $vOffset = Math.abs($distToBottom - $("#preview-box").outerHeight())

    if ($distToBottom > $("#preview-box").outerHeight()) {
      $container.css("top", $position.top);
    } else {
      $container.css("top", $position.top - $vOffset - settings.offset);
    }

    if ($position.left > ($("#preview-box").outerWidth())) {
      $container.css("left", $position.left - $("#preview-box").outerWidth() - settings.offset)
    } else {
      $container.css("left", $position.left + $this.outerWidth() + settings.offset)
    }

    if (settings.animate) {
      $container.animate({ opacity: 'show' }, 'medium');
    } else {
      $container.show();
    }
  }

};
