/// <reference path="jquery-1.4.4-vsdoc.js"/>
/*
COPYRIGHT (C) 2011 Raynald Messi�

THIS FILE IS PART OF SCRUMPILOT.

SCRUMPILOT IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF 
THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

SCRUMPILOT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT
EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER
GENERAL PUBLIC LICENSE FOR MORE DETAILS.

YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH SCRUMPILOT. 
IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.

Inspired by : Marco Kuiper (http://www.marcofolio.net/)
and  http://www.webspeaks.in/2010/03/twitter-api-how-to-create-stream-of.html

*/

(function ($) {
    $.fn.unlimitedscroll = function (url, itemfunction, options) {
        var defaults = {
            pageSize: 15,
            maxPages: 1,
            IndexFieldName: null,
            timer: 0,
            timerUrl: null,
            on_complete: null,
            on_loading: null,
            on_loaded: null,
            on_error: null
        };

        var options = $.extend(defaults, options);

        function maxIndex(index1, index2) {
            if (index1 && index2)
                return (index1 > index2) ? index1 : index2;
            else if (index1 || index2) // if one of them is not define
                return index1 ? index1 : index2;
            else // if there are not define
                return null;
        }

        return this.each(function () {
            var currentPage = 1;
            var myInterval = -1;
            var lastIndex; // use to now which new items could be retrieve by timer
            var obj = $(this);

            var load = function () { // Load items and append it in dom (use for initial load and scroll)
                if (myInterval > 0) // Stop the timer during loading
                    clearInterval(myInterval);
                try {
                    $.getJSON(url, { first: (currentPage - 1) * options.pageSize, last: (currentPage * options.pageSize) - 1 },
                       function (data) {
                           if (data && data != 0) {
                               $.each(data, function (i, item) {
                                   obj.append(itemfunction(item).html());
                                   lastIndex = maxIndex(lastIndex, item[options.IndexFieldName]);
                               });

                               if (options.timer > 0) addTimer(); // set autorefresh
                           }
                           if (options.on_complete) options.on_complete();
                           if (options.on_loaded) options.on_loaded();
                       });
                } catch (ex) {
                    if (options.on_loaded) options.on_loaded();
                    if (options.on_error) options.on_error(ex);
                }
            };

            function addTimer() {
                if (options.timerUrl) { // Check if there an Url
                    myInterval = window.setInterval(function () {
                        $.getJSON(options.timerUrl, { lastindex: lastIndex }, function (data) {
                            if (data && data != 0) {
                                $.each(data, function (i, item) {
                                    var element = itemfunction(item);
                                    obj.prepend(element);
                                    if (element != null){
                                    element.fadeOut(0, function () {
                                        element.fadeIn(3000);
                                        //element.effect('highlight');
                                    });}
                                    lastIndex = maxIndex(lastIndex, item[options.IndexFieldName]);
                                });
                            }
                        });
                    }, options.timer);
                }
            }

            // Append a scroll event handler to the windows
            $(window).scroll(function (e) {
                // We check if we're at the bottom of the scroll windows
                if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                    // If we're at the bottom, show the overlay and retrieve the next page
                    if (options.maxPages < 0 || (options.maxPages < currentPage)) {
                        if (options.on_loading) options.on_loading();
                        currentPage++;
                        load();
                    }
                }
            });
            
            // Append a scroll event handler to the container
	$("#windowscroll").scroll(function() {
		// We check if we're at the bottom of the scrollcontainer
		if ($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight()) {
			// If we're at the bottom, show the overlay and retrieve the next page
			currentPage++;
			
			if(currentPage > 10) {
				alert('We should not spam the Twitter API with calls. I hope you get the idea!');
				return false;
			}
			
			$("#overlay").fadeIn();
			load();
		}
	});

            // Load the first time
            load();
        });
    };
})(jQuery);
