/* Javscript Category Folding
 * by Justin Davis <jrcd83 ATAT gmail DIZOT com>
 * (c) 2009 Sandstone Stickers
 */

var SS = new Object;

SS.STICKER_SIZES = [ 'mini', 'large', 'bumper' ];
SS.IMAGE_BASE    = '/img/';

jQuery.fn.toggle_foldbutton = function ( isVisible )
{
    var imgSrc;

    if (!isVisible)
        imgSrc = SS.IMAGE_BASE + '/minus.bmp';
    else
        imgSrc = SS.IMAGE_BASE + '/plus.bmp';

    $(this).children('img.foldbutton').attr( 'src', imgSrc );

    return this;
};

jQuery.fn.toggle_fold = function() {
    this.filter('div.menuitem').each( function() {
        var isVisible = $(this).data('isVisible');
        if ( isVisible == undefined ) isVisible = true;

        $(this).toggle_foldbutton(isVisible);
        isVisible = !isVisible;

        var methodName = ( isVisible ? 'show' : 'hide' );
        $(this).children('div.menuitem')[methodName]();

        $(this).data( 'isVisible', isVisible );
    });
    return this;
};

$(document).ready(
    function () {
        // Add a fold button for every parent menu
        var imgElem = $('<img class="foldbutton" src="'+SS.IMAGE_BASE+'/plus.bmp" />');
        $('.menuitem').filter( function () {
                return $(this).children('.menuitem').size() > 0;
            } ).each( function () {
                imgElem.clone().insertAfter($(this).children('a'));
            } );

        var activeDIV = $('#active_menuitem').parent();
        if ( activeDIV.size() ) {
            // If a menu is selected, leave ancestors unfolded
            activeDIV.andSelf().parents().toggle_foldbutton();
            activeDIV.parents().siblings().toggle_fold();
            activeDIV.siblings().children('div.menuitem').toggle_fold();
            activeDIV.siblings().toggle_fold();
            activeDIV.children().toggle_fold();
        }
        else {
            // Otherwise, leave top level menus unfolded
            $('#sidebar').children('div.menuitem').children('div.menuitem').toggle_fold();
            $('#sidebar').children('div.menuitem').toggle_foldbutton();
        }

        $('img.foldbutton').bind( 'click',
            function (e) {
                $(this).parent().toggle_fold();
            } );
    }
);

