(function($){ // closure
    MemberfuseJ = {
        /**
         * A collection of reusable loading animations for convenience.
         */
        loaders: {
            // Big ol' swirly circle...
            large: $('<img src="/themes/global/default/normal/images/loading.gif" ' + 'class="loading" />'
            ),
            none: null
        },

        headSlide: function(parent){
            jQuery("a.privacy_title").click(function () {
                var target = jQuery("span.privacy_title_arrow", this);
                if(target.css('background-position') == '-32px -48px') {
                    target.css('background-position','-48px -48px');
                }
                else {
                    target.css('background-position','-32px -48px');
                }
                jQuery(this).next("div.privacy_settings").slideToggle('fast');
            });
        },

        initImageCropper: function(ratio_w, ratio_h, minWidth, minHeight){
            // some defaults
            //var start_x =
            jQuery('#tmp_slide_img').Jcrop({
                setSelect: [ 0, 0, 80, 130 ],
                bgColor: 'blue',
                onChange: onEndCrop,
                onSelect: showPreview,
                bgOpacity: .8,
                sideHandles: true
            });
        },

        /**
         * The "delete_icon" plugin makes the "delete" link for the element
         * appear and disappear as a part of the hover-state.
         */
        ui_delete_button: function(){
            return this.each(function(){
                var $el = $(this);

                var $del = $el.delegate('a.delete').hide();

                $del.length && $el.hover(
                    function(){ $del.show(); },
                    function(){ $del.hide(); }
                );
            }); // END this.each
        }, // END ui_delete_button

        /**
         * Register all the "ui_*" plugins with jQuery for use throughout the app.
         */
        init_ui_plugins: function(){
            var pattern = /^ui_/;

            $.each(MemberfuseJ, function( key, value ){
                if ( key.match(pattern) ) $.fn[key] = value;
            });

            return MemberfuseJ; // for method chaining
        }, // END init_plugins


        /**
         * The ".update_list" element is used on the user and admin dashboard pages
         * to hold activities. Since we're loading those via Ajax now, there are
         * some additional steps to wire up the paginate and delete events. This
         * method initializes that behavior with "delegate()" and "live()" methods
         * so that they don't have to be re-initialized after each Ajax request.
         */
        init_update_list: function(){
            var $update_list = $('.update_list');

            /**
             * Clicking on the paginator for the $update_list should load() the
             * next page via Ajax and display an appropriate loading animation in
             * the meantime.
             */
            $update_list.delegate('a[rel=page]', 'click', function(){
                $update_list.html(MemberfuseJ.loaders.large).load(this.href);

                return false;
            });

            /**
             * Delegating the ".update_item" events to the $update_list means we
             * don't have to re-initialize them on every Ajax load.
             */
            $update_list.delegate('.update_item', {
                /**
                 * The "hover" event will toggle the "a.delete" link, if it exists.
                 */
                'hover': function(){
                    $(this).find('a.delete').toggle();
                },
                /**
                 * The "cancel" event returns the ".update_item" opacity to normal.
                 */
                'cancel': function(){
                    $(this).fadeTo('fast', '1.0');
                },
                /**
                 * The "kill" event will cause the ".event_item" to fadeOut(),
                 * taking its parent ".event_day" element if it's the last to go.
                 */
                'kill': function(){
                    $(this).fadeOut(function(){
                        if ( !$(this).siblings('.update_item:visible').length )
                            $(this).closest('.update_day').fadeOut();
                    });
                }
            }); // END delegate .update_item

            /**
             * Clicking the "a.delete" link triggers an Ajax GET request to the
             * that href, which is expected to reply with an HTML snippet to use
             * as the ".modal.confirm" dialog.
             */
            $update_list.delegate('a.delete', 'click', function(){
                var $button = $(this);

                $button.closest('.update_item').fadeTo('fast', '0.4');

                /**
                 * @todo Check that the response contains ".modal.confirm", as expected.
                 */
                $.get(this.href, function(response, status){
                    if ( status == 'success' && $(response).is('.modal.confirm') )
                        $(response).appendTo('body').data(
                            'caller', $button
                        ).trigger('open.modal');
                });

                return false;
            });

            $update_list.html(MemberfuseJ.loaders.large).load(
                $update_list.attr('rel')
            );

            return MemberfuseJ; // for method chaining
        }, // END init_update_list


        init_status_updates: function(){
        	$('#status li').live('hover', function(){
        		$(this).find('a.delete').toggle();
        	});

        	$('#status a.delete').live('click', function(){
        		var $link = $(this);

        		$.get(this.href, function(response_text, success, response_object) {
        			paginator.refreshPage();
        		});

        		paginator.decrementOffset();

        		return false;
        	});

        	// bind on key up event
			$('#enter_message').live('keyup', function(){
				var new_length = $(this).val().length;
				var chars_left = ((char_count - new_length) < 0) ? 0 : (char_count - new_length);
				$('span.char_count').html(chars_left + ' Characters Left');

				if (chars_left < 0)
				{
					$('span.char_count').addClass('red');
				}
				else
				{
					$('span.char_count').removeClass('red');
				}
			});
        }, // END init_status_updates

        add_latest_status_message: function(user_id) {
        		if (ajaxBusy) {return;}
                $.ajax({
                        url: '/statusupdate/status/laststatusupdate/user/' + user_id,
                        beforeSend:function() {ajaxBusy = true;},
                        success: function(latest_message){
                                if (!$('#status_message_list:visible').length)
                                {
                                        $('.no_updates').hide();
                                        $('#status_message_list').show();
                                }
                                $('#status_message_list:first-child').prepend(latest_message).fadeIn('slow');
                        },
                        complete: function() {ajaxBusy = false;}
                });
                $('#enter_message').val('');

                paginator.incrementOffset();
        },

        /**
         * The ".modal" element is usually provided as the response to an Ajax
         * request. The top-level element should be <div class="modal" />. This
         * method initializes events particular to that dialog for use throughout
         * the UI. It delegates to the document, so it's safe to initialize in
         * document.ready().
         */
        init_modal: function(){
            var $modal = $('.modal').die();

            /**
             * Registering the $modal events as "live()" ensures that they're
             * always available, even if no $modal element exists on the page
             * yet. That's important for an element that is added dynamically.
             */
            $modal.live({
                /**
                 * The "kill" event removes the $modal elegantly.
                 */
                'kill.modal': function(){
                    $(this).fadeOut(function(){
                        $(this).remove();
                    });
                },
                /**
                 * The "open" event reveals the $modal, which must already be
                 * appended to the <body> element. It also positions it over the
                 * "caller" element, if that has been set by the opening element.
                 */
                'open.modal': function(){
                    var $modal = $(this);

                    var offset = $modal.data('caller').offset();

                    if ( offset ) $modal.offset({
                        top: offset.top,
                        left: offset.left - $modal.width()
                    })

                    $modal.fadeIn();

                    return false;
                } // END open.modal
            }); // END $modal.live

            return MemberfuseJ; // for method chaining
        }, // END init_modal


        /**
         * The ".modal.confirm" element is specific to controls that require an
         * additional confirmation step. They'll usually have two buttons -- "confirm"
         * and "cancel" -- that trigger the Ajaxed submit (if appropriate) or the
         * "kill.modal" event, respectively.
         */
        init_modal_confirm: function(){
            /**
             * The "cancel" button should "kill" the modal when clicked.
             */
            $('.modal.confirm button#cancel').die().live('click', function(){
                var $caller = $(this).closest('.modal').data('caller');

                $caller && $caller.trigger('cancel');

                $(this).trigger('kill.modal');
            }); // END button#cancel live click

            /**
             * A "form.ajax" element submit()s asynchronously via Ajax and kills
             * the modal if successful. Failure should be handled by some other
             * mechanism.
             */
            $('.modal.confirm form.ajax').die().live('submit', function(){
                var $form = $(this);

                var $modal = $form.closest('.modal');

                var $caller = $modal.data('caller');

                $.post($form.attr('action'), {'confirm': 1}, function(response, status){
                    if ( status == 'success' && $caller )
                        $caller.trigger('kill');
                });

                $modal.trigger('kill');

                return false;
            }); // END form.ajax submit()
        }, // END init_modal

        // Keep it around in case someone tries jQuery.noConflict(true)... :[
        jQuery: jQuery
    }; // END MemberfuseJ

    $(function(){ // document.ready
        (function(M){ // closure
            M.init_ui_plugins();
            M.init_status_updates();
            M.init_modal();
            M.init_modal_confirm();
        })(MemberfuseJ);

        // This needs to work on all ".datePicker" elements...
        $('.datePicker').live('mousedown', function(){
            $(this).datepicker();
        });
        
        $('div[class^="discussion_depth"] .bottom .hide_replies a').live('click', function(){
        	var post_id = $(this).attr('rel');
        	var selector = 'div[class*="reply_to_' + post_id + '"]'
        	
        	//Actually hide the descendant posts
        	$(selector).toggle();
        	
			$(this).parents('span.hide_replies').toggle();
			$(this).parents('div.bottom').find('.show_replies').toggle();
		});
        
        $('div[class^="discussion_depth"] .bottom .show_replies a').live('click', function(){
        	var post_id = $(this).attr('rel');
        	var selector = 'div[class*="reply_to_' + post_id + '"]'
        	
        	//Actually hide the descendant posts
        	$(selector).toggle();
        	
			$(this).parents('span.show_replies').toggle();
			$(this).parents('div.bottom').find('.hide_replies').toggle();
		});
    }); // END document.ready

})(jQuery.noConflict()); // END closure

var ajaxBusy = false;

