$(document).ready(function(){
    /* We want the shopping cart to move with the page scroll.
     * The smoothest way to achieve this is to set the cart's position
     * to fixed once we have scrolled past it's starting position.
     */
    var cart = $("#sideshoppingcart"), // Get cart element
        pos = $(cart).offset(); // Get starting position of the cart

    $(window).scroll(function(){
        // If we have gone past the div's starting position, change its CSS position
        if($(window).scrollTop() > pos.top){
            $(cart).css('position', 'fixed')
                   .css('top', '0px');
        }else{
            $(cart).css('position', 'static');
        }
    });

    // Use current category to hide other sidebar category groups
    // Find the current category name in a group name, otherwise
    // find the current category name in a category in a group.
    var category = $("h3.wpsc_category_boundary"),
        sidebar = $("#sidebar .widget");

    if($(category).length == 1){
        var name =  $(category).text();
        name = $.trim(name);

        // Do any category groups have this name?
        var groups = $(sidebar).find('h4.wpsc_category_title'),
            group = false;
        $.each(groups, function(i, val){
           if($(this).text() == name){
               group = true;
               $(this).parents('div.wpsc_categorisation_group').addClass('show');
           }
        });

        if(!group){
            // If we did not find any group matches, lets try to find
            // a category match.
            var categories = $(sidebar).find('a.wpsc_category_link');
            $.each(categories, function(i, val){
               if($.trim($(this).text()) == name){
                   $(this).parents('div.wpsc_categorisation_group').addClass('show');
               }
            });
        }
    }

    // Since the above will fail for single_product.php, let's use a
    // different method to match IDs instead of names

    // Match for each ID
    var categories = $(sidebar).find('a.wpsc_category_link');
    if($("#prodidmatch").length > 0){
        $("#prodidmatch span").each(function(){
           var id = $(this).text();
           id = $.trim(id);

           $.each(categories, function(i, val){
              if($(this).attr('rel') == id){
                  $(this).parents('div.wpsc_categorisation_group').addClass('show');
              }
           });
        });
    }

    if($(sidebar).find('div.wpsc_categorisation_group.show').length > 0){
        $(sidebar).find('div.wpsc_categorisation_group').each(function(){
           if(!$(this).hasClass('show')){
               $(this).hide();
           }
        });
    }
});
