;(function($){
  /*
   * Plugin Definition
   */
  $.fn.contentPagination = function(options){
    // build main options before element iteration
    var opts = $.extend({}, $.fn.contentPagination.defaults, options);

    // iterate and create pagination for each matched element
    return this.each(function() {
      el = $(this);

      //Select all elements within the content area)
      var children = el.children('address, blockquote, dl, h1, h2, h3, h4, h5, h6, hr, ol, table, p, pre, ul, div');
      var totalPages = 1;
      var nextPageTopPosition = startTopPosition = el.offset().top;

      //alert(nextPageTopPosition);
    
      
      do{
        nextPageTopPosition = parseInt(nextPageTopPosition) + parseInt(opts.pagingHeight);
        alert('nextPageTopPosition :: '+nextPageTopPosition+' pagingHeight :: '+opts.pagingHeight);
        
        var tempEl = $.fn.contentPagination.getElementNearTopPosition(children, nextPageTopPosition);

        if(tempEl !== false){
          tempEl.addClass(opts.pageBreakClass);
        }

        totalPages++;

      }while(tempEl !== false);        

      
      children.wrapAll('<div class="paginationSlider"></div>');

      //Build the pagination
      if(totalPages > 1){
        el.after('<div class="pagination"><ul></ul></div>');
      }
    });    
  };
  
  $.fn.contentPagination.next = function(){
    
  };

  $.fn.contentPagination.previous = function(){
    
  };

  $.fn.contentPagination.getPage = function(pageNum){
    
  };

  // This is a linear function for now searching for elements with the closest top position to the desired top position
  $.fn.contentPagination.getElementNearTopPosition = function(els, topPos){
    var closestDistance = -1;
    var closestEl = false;
    var tempDistance = 0;
    var lastElPos = els.find(':last').offset();

    for(i=0; i<els.length; i++){
      var offset = els.eq(i).offset();      
      //alert("offset :: "+ offset.top + " topPos :: "+topPos);

      if(topPos < lastElPos.top){
        if(closestDistance == -1){
          closestDistance = Math.abs(offset.top - topPos);
          closestEl = els.eq(i);
        }
        else{
          tempDistance = Math.abs(offset.top - topPos);
          if(closestDistance > tempDistance){
            closestDistance = tempDistance;
            closestEl = els.eq(i);
          }
        }
      }
      else{
        return false;
      }
    }

    return closestEl;
  };


  // Debugging function
  function debug($obj) {
    if (window.console && window.console.log){
      alert($obj)
    }
  };

  // plugin defaults
  $.fn.contentPagination.defaults = {
    pagingHeight: "1000",
    slideSpeed: "500",
    pageBreakClass: "pagebreak",
    startingPage: 1
  }

})(jQuery);

