/**
 * Simple Ajax Pager
 *
 * This is a custom jQuery plugin that I created to specifically retrieve 
 * paged data via AJAX/JSON.
 *
 * @TODO add disabled class to the next/previous elements, if there is not any data in that direction.
 */

(function($){
    $.fn.sajaxpager = function(options) {
        // the container object
        var container = null;

        // the parent object of the container
        var obj = null;

        // default options
        var defaults = {
            previous_id: null,
            next_id: null,
            url: null,
            results_per_page: 3,
            render_item_callback: function(obj){},
            current_page: 1
        };

        // current configuration options for the plugin
        var options = $.extend(defaults, options);

        /**
         * Uses ajax to retrieve the current page data from the server.
         *
         * @param integer $page The page number that you want to retrieve.
         */
        var get = function($page){
            $.post(
                options.url, 
                {
                    rows: options.results_per_page,
                    page: $page
                }, 
                function(data){ parse(data); }
            );
        };

        /**
         * Parses the data returned from the server.
         *
         * @param string $data The data returned from the server
         */
        var parse = function($data){
            var $data = $.parseJSON($data);

            // remove the items in the container
            container.html('');

            if ( $data.rows.length > 0 ){
                // loop through the returned items and populate the container
                for(var i = 0; i < $data.rows.length; i++){
                    container.append( options.render_item_callback($data.rows[i]) );
                }
            }
        }

        return this.each(function(){
            container = $(this);
            obj = container.parent();

            get(options.current_page);

            if ( options.previous_id != null ) {
                var previous_link = $('#'+options.previous_id, obj);
                previous_link.click(function(){
                    options.current_page = (options.current_page - 1);
                    get(options.current_page);
                });
            }

            if ( options.next_id != null ) {
                var next_link = $('#'+options.next_id, obj);
                next_link.click(function(){
                    options.current_page = (options.current_page + 1);
                    get(options.current_page);
                });
            }
        });
    };
})(jQuery);

