// http://github.com/juggy/jquery-popover
// http://docs.jquery.com/Plugins/Authoring
// http://net.tutsplus.com/articles/news/you-still-cant-create-a-jquery-plugin/
jQuery.fn.popover = function(a){
  
  var openedPO = null;
  //header = $(a.header).detach();
  //content = $(a.content).detach();
  //var header = a.header
  //var contentUrl = a.contentUrl;
  
  // openEvent = a.open;
  // closeEvent = a.close;
  
  hidePopover = function(content){
    content.removeClass("active");
    content.attr("style", "");
    
    // this way if scrollbars were displayed, then the window resized so that
    // no scrollbars are needed, and then the popover is opened again,
    // max-height will be calculated again (without this, scrollbars would
    // appear again)
    content.children(".content").css("max-height", "");
    
    //if($.isFunction(closeEvent)) closeEvent();
    
    content.hide();
    
    openedPO = null;
    
    $(document).unbind("click.popover touchend.popover");
    
    return false;
  }
  
  // it uses button
  showPopover = function(buttonJqueryObject,content) {
    
    // I've replaced old "this" with "buttonJqueryObject"
    //triangle = $(".floater > .triangle", buttonJqueryObject);
    triangle = $(".triangle", content);
    leftOff = 0;
    topOff = 0;
    docWidth = $(document).width();
    docHeight = $(document).height();
    triangleSize = parseInt(triangle.css("border-bottom-width"));
    contentWidth = content.outerWidth();
    // height of header + content divs as the triangle is absolutely positioned
    contentHeight = content.outerHeight();
    buttonWidth = button.outerWidth();
    buttonHeight = button.outerHeight()
    offset = button.offset();
    
    // Calculate topOff (the space between the top of the document and the
    // top of the popover; the triangle is not considered part of the popover)
    topOff = offset.top + buttonHeight + triangleSize;
    
    // resizes the popover so that it doesn't extend beyond the bottom of the
    // window (previously it was resized to not extend beyond the bottom of the
    // document, but I think it's better that it doesn't extend beyond the window)
    // (I don't understand what's the role of triangleSize here)
    //diffHeight = docHeight - (topOff + contentHeight + triangleSize );
    diffHeight = $(window).height() - (topOff + contentHeight + triangleSize );
    if(diffHeight < 0){
      content.height(content.height() + diffHeight);
    }
    
    //Calculate leftOff
    leftOff = offset.left + ( buttonWidth - contentWidth)/2;
    diffWidth = 0
    if(leftOff < 0){
      //out of the document at left
      diffWidth = -leftOff;
    }else if ( leftOff + contentWidth > docWidth){
      //left of the screen right
      
      diffWidth = leftOff + contentWidth - docWidth;
    }
    
    //position content
    triangle.css("left", contentWidth/2 - triangleSize + diffWidth);
    
    // resize the content for overflow (notice that the 'content' variable is
    // the whole 'floater' div, not the 'content' div). Without this overflowing
    // content would be rendered outside the element's box.
    content.children(".content").
        css("max-height",
            content.height() - 40); // 40px is the header height, set in popover.css (~L41)
//                parseInt(content.children(".header").css("height")));
    // For some reason jQuery's offset doesn't work as expected
    //content.offset({ top: topOff, left: leftOff - diffWidth });
    // so
    content.css({ top: topOff, left: leftOff - diffWidth });
    
    //$(document).click(function(event){
    // http://api.jquery.com/unbind/
    $(document).bind('click.popover touchend.popover', function(event) {
      if ($(event.target).parents(".popover").length === 0){
        return hidePopover(content);
      }
    });
    
    content.show();
    //Timeout for webkit transitions to take effect
    window.setTimeout(function(){content.addClass("active");}, 0)
    //if($.isFunction(openEvent)) openEvent();
    openedPO = buttonJqueryObject;
    
    return false;    
    
  }
  
  // $(this).live(...  doesn't work, http://paulirish.com/2010/on-jquery-live/
  // so...
  // http://stackoverflow.com/questions/500246/how-do-i-get-a-jquery-selectors-expression-as-text
  var s = $(this).selector;
  $(s).live('click', function() {
      if (!$(this).hasClass('popover')) {
        //$(this).addClass("popover");
        //$(this).append(
        content =
            $('<div class="floater"><div class="triangle"></div>' +
              '<div class="header">' + $(this).attr('data-popover-header') +
              '</div><div class="content"></div></div>')
                .appendTo($('<div class="popover"></div>').appendTo('body'));
      }
      
      
      
      // wraps the DOM element 'this' in a jQuery object
      button = $(this);
      
      
      // content is actually the whole floater div
      // content = $(".floater", this);
      
      
      //already opened
      // inside (plugin) methods, 'this' is a reference to the current jQuery object (not the DOM element)
      // http://docs.jquery.com/Plugins/Authoring
      if(openedPO === this){
        return true;
      }else if(openedPO != null){
        //Close the previous one
        openedContent = $(".floater", openedPO);
        hidePopover(openedContent);
      }
      

      buttonJqueryObject = this;
      var contentUrl = $(this).attr('data-popover-content-url');
      //$('.floater .content', buttonJqueryObject).load(contentUrl, function() {
      $('.content', content).load(contentUrl, function() {
        showPopover(buttonJqueryObject, content);
      });
      
       return false; // crucial, it doesn't work without it
      
    });

    //});
  //});   end this.each
};

