/*global jQuery */
(function($) {

    $.fn.streamScroll = function(params) {

        params = $.extend({
            guardFormatter: function () {
                return $('<li class="dyn_guard">&nbsp;</li>');
            }
        }, params);

        return this.each(function() {
            var $_this = $(this);
            var do_init = true;
            var loader = null;

            $_this.data("ssc_params", params);

            // Apply fixed positioning to the page footer, increase stream's
            // bottom margin
            $("#footer, #footer_lite").addClass('ajax_stream');
            $("#primary ul.pager").hide();
            $_this.addClass("ajaxified_stream");

            $(window).scroll(function () {
                guardCheck($_this);
            });

            // Initialize
            $_this.trigger("lowwatermark");

            // =================================================================
            //    Public API
            // =================================================================
            this.appendContent = function (content) {
                if (!content) {
                    console.log("Empty stream content");
                    $_this[0].errorFallback();
                    return false;
                }

                var params = $_this.data("ssc_params");
                var obj = $(content);

                $_this.append(obj);

                var cnt = $("> li", $_this).length;
                if ($(obj).length > 3) {
                    var guard = params.guardFormatter();
                    var pos = cnt - 2;
                    guard.insertAfter($("> li:nth-child(" + pos + ")", $_this));
                } else {
                    $_this[0].errorFallback();
                }

                if (do_init) {
                    do_init = guardCheck($_this);
                }

                // Reinitialize Noovo stuf
                setTimeout(function () {
                    NOOVO.Inline.init();
                    NOOVO.util.showHide();
                    NOOVO.favoritizer.init();
                    sliderInit();
                    $(".set-blogmode").each(NOOVO.util.setMouseoverHandler);
                    if ($("#inoovo").length == 0) {
                        $('.lightning', obj).nooxExplain();
                    }
                    $(obj).urlBookmarkRewriter();
                    $('.editor_console', obj).editorConsole();
                    $('.add_to_link', obj).add_to_link();
                    $('a.add_friend_link', obj).addFriendButton({
                        onloadhandler: function (message) {
                            NOOVO.ga.trace("people", "add");
                            $("#friend_stream_message").remove();
                            var msg = $('<div id="friend_stream_message">' + message + '</div>')
                                .insertBefore($_this).effect("highlight", { color: "#ffff33" }, 2000);
                            setTimeout(function () {
                                msg.fadeOut("normal", function () {
                                    msg.remove();
                                });
                            }, 5000);
                        },
                        onerrormessage: function (message) {
                            $("#friend_stream_message").remove();
                            var msg = $('<div id="friend_stream_message">' + message + '</div>')
                                .insertBefore($_this).effect("highlight", { color: "#ffff33" }, 2000);
                            setTimeout(function () {
                                msg.fadeOut("normal", function () {
                                    msg.remove();
                                });
                            }, 5000);
                        }
                    });
                    $(".nothing_here", $_this).remove();
                    NOOVO.util._equalHeight(1);
                }, 100);
            };

            this.showLoader = function () {
                if (!loader) {
                    loader = $('<div class="stream_loader simpleLoader"></div>').insertAfter($_this);
                } else {
                    loader.show();
                }
            };

            this.hideLoader = function () {
                if (loader) {
                    loader.hide();
                }
            };

            this.errorFallback = function () {
                $_this.removeClass("ajaxified_stream");
                $("#footer, #footer_lite").removeClass('ajax_stream');
                $_this[0].hideLoader();
                NOOVO.util._equalHeight(1);
            };

            this.reinitialize = function () {
                $_this.empty();
                do_init = true;
                $_this.trigger("lowwatermark");
            };
        });

        // =====================================================================
        //    Private stuff
        // =====================================================================
        function guardCheck(container) {

            var guard = $('.dyn_guard', container);

            if (guard.length == 0) {
                return false;
            }

            var tlow = $(window).height();
            var gpos = guard.offset().top - $(document).scrollTop();

            if (gpos <= tlow) {
                guard.remove();
                container.trigger("lowwatermark");
                return true;
            } else {
                return false;
            }
        };

        function sliderInit () {
            var sliders = [];
            function updateValue(off) {
                $("#"+this.id).prev()[0].value = off;
            }

            var i, id, slider, div, inps = $("input");

            $("input").each(function (i) {
                id = this.id || "";
                if (id && id.slice(0,13) == "id_nooximity_" && $("#" + id + "_slcontainer").length == 0) {
                    div = $('<div id="'+id+'_slcontainer" class="weightcontainer"></div>')[0];
                    $(div).css("width", "110px");
                    this.parentNode.insertBefore(div, this.nextSibling);

                    slider = new NOOVO.widgets.Slider(div.id, "horizonal", 222);
                    slider.onChange = updateValue;
                    slider.onChange.el_id = id;
                    slider.setStart(parseInt(this.value));
                    slider.show();

                   sliders[sliders.length] = slider;
                }
            });
        };
    };
})(jQuery);
