/**
 * jqPageFlow v0.1b - jQuery plugin
 * Copyright (c) 2009 Barry Roodt (http://calisza.wordpress.com)
 *
 * Licensed under the New BSD license.
 *
 * This plugin makes scrolling pagination possible (such as that found on Google Reader and dzone.com).
 * An example can be found at http://flexidev.co.za/projects/jqpageflow
 * Please check http://code.google.com/p/flexidev/downloads/ for the latest version
 *
 * Special thanks to Christopher Mills (http://imod.co.za) for the help with naming and promoting this plugin
 *
 */

;(function($){
   $.flexiPagination = {
        loading: false,
    
        defaults: {
         url: "",
         currentPage: 0,
         totalResults: 100,
         perPage: 25,
         container: "body",
         pagerVar : "p",
         loaderImgPath: "images/loader.gif",
         debug : 0,
         icons: null,
         mode: "json",
         loadcontainer: "body"
    },

        // enable initial calls.
        loadContent: function(url, config) {

                $.ajax({
                   type: "GET",
                   dataType: config.mode,
                   url: url,
	 	cache: false,
                   success: function( result){
    
                       if (result) {

                           // custom html from json.
                           var html = '';

                         if(config.mode == "json") {
                               // set the total count.
                               config.totalResults = result.totalCount
                                                  
                               for(var i = 0; i < result.data.length; i++) {
                                    
                                html += '<div class="guestbook-item">';
                                html += '<div class="createdby">';
                                html += '    <span>Namn</span>';
                                html += '    <p>'+result.data[i].Name+'</p>';
                                html += '</div>';

                                 if(result.data[i].Url != '') {
                                    html += '<div class="url">';
                                    html += '    <span>Url</span>';
                                    html += '    <p><a href="'+result.data[i].Url+'">'+result.data[i].Url+'</a></p>';
                                    html += '</div>';
                                  }
                                 
                                  var msg = result.data[i].Message;
                                  if(config.icons != null) {
                                    for(var j = 0; j < config.icons.items.length; j++) {
                                      msg = msg.replace(config.icons.items[j].pattern, '<'+'img src="' + FOLDER + '/' + config.icons.items[j].imgsrc +'" alt="" '+'/>');
                                    }
                                  }

                                  html += '<div class="message">';
                                  html += '    <span>Meddelande</span>';
                                  html += '    <p>'+msg.replace(/(\r\n|[\r\n])/g, '<br />')+'</p>';
                                  html += '</div>';

                                  html += '<div class="posted">';
                                  html += '    <span>Postad</span>';
                                  html += '<p>'+result.data[i].PostedDateString+'</p>';
                                  html += '</div>';
                                  html += '</div>';
                                    
                               }
                           }
                             
                           if(config.mode == "html") {
                              html = result;
                           }
                     
                           $(config.container).append( html );

                           config.currentPage++;
              } else {
                // prevent any further attempts to execute the ajax call since the backend is not returning a useable result.
                config.currentPage = -1;
              }

                   },
                   complete: function(){
                         // allow ajax call to be executed again if necessary and hide the loader
                       $.flexiPagination.loading = false;
                       $("#jqpageflow-block").hide();
                   }
               });

             }
  };

  $.fn.extend({
    flexiPagination:function(config) {
    
      // initialize our config object
      var config = $.extend({}, $.flexiPagination.defaults, config);
      $.flexiPagination.loading = false;
          
         // set default container element as body if config var is empty
         config.container = (config.container != "") ? config.container : "body";
        config.loadcontainer = (config.loadcontainer != "") ? config.loadcontainer : "body";

         // create and append our progress indicator div to the body content, then make sure our css is applied
         $(config.loadcontainer).append("<div id='jqpageflow-block'><img src='" + config.loaderImgPath + "' /><span id='jqpageflow-text'></span></div>");
         $("#jqpageflow-block").addClass("jqpageflow-loader");
         $("#jqpageflow-text").addClass("jqpageflow-loadertext");
         

            if(config.currentPage == 0 && !$.flexiPagination.loading) {
                $.flexiPagination.loadContent(config.url, config);
                $.flexiPagination.loading = true;
            }
         
         // bind the window's scroll event to a custom function
      $(window).scroll(function(){
        
        // work out whether we need to fire our ajax call or not
           var scrollPosition = $(this).scrollTop();
           var height = ($(document).height() - $(this).height());
        
           if ( config.currentPage >= 0 && (config.perPage * (config.currentPage + 1) < config.totalResults)  
           && !$.flexiPagination.loading && scrollPosition == height) {
             
               // this automatically prevents any further attempts to execute another ajax call until the current ajax call has returned a result
               $.flexiPagination.loading = true;
    
                   var url = config.url;

               if (url != "") {
            url += (config.url.indexOf("?")!==-1 ? "&" : "?") + config.pagerVar + "=" + (config.currentPage + 1);
          } else {
            // the default url is the current window location with the pageVar and currentPage values attached
            url = window.location + (window.location.search != '' ? "&" : "?") + config.pagerVar + "=" + ( config.currentPage + 1 );
          }
          
          // update the loader text and display the loader.
          $("#jqpageflow-text").text('Laddar in ' + (config.perPage * ((config.currentPage > 0) ? config.currentPage : 1)) + ' av ' + config.totalResults);
          $("#jqpageflow-block").show();

                    $.flexiPagination.loadContent(url, config);
           }
      });
      
      return this;
    }
  });
  
})(jQuery);
