﻿var messageCollapse = function (value) { return value.replace('Expand', 'Collapse'); };
var messageExpand = function (value) { return value.replace('Collapse', 'Expand'); };
var toggleMessageExpanded = function (value) { return (value.indexOf('Expand') >= 0); };

var toggleMessage = function (value) {
    if (toggleMessageExpanded(value)) {
        return messageCollapse(value);
    } else {
        return messageExpand(value);
    }
    return value;
};

$(document).ready(function () {
    function Init() {

		$('.BookstoreGroupItems ul').each(function () {
			$(this).attr("eh", $(this).height());
			$(this).attr("ch", $(this).height());
			
			var displayCount = $(this).children('li').length;
			    			
			var height = 0;
			var heightC = 0;
			$(this).children('li').each(function() { 
				if(++heightC <= 5) {
					height += $(this).outerHeight(true);
				}
			});
			
			$(this).attr("ch", height);
			$(this).stop().animate({'height': height + 'px'}, 250);
        });
    }

    Init();

    $('.BookstoreGroup .ExpandAll').each(function () {
        $(this).click(function () {
            var message = $('.BookstoreGroup .ExpandAll').html();

            if (toggleMessageExpanded(message)) {
                $('.BookstoreGroup .ExpandGroup').each(function () {
                    $(this).click();
					$(this).html(messageCollapse($(this).html()));
                });
            } else {
                $('.BookstoreGroup .ExpandGroup').each(function () {
                    $(this).click();
					$(this).html(messageExpand($(this).html()));
                });
            }

            $('.BookstoreGroup .ExpandAll').html(toggleMessage(message));
            return false;
        });
    });

    $('.BookstoreGroup .ExpandGroup').each(function () {
        $(this).click(function () {
            var parentID = $(this).attr('parentID')
				,message = $(this).html()

			var u = $('#' + parentID + " ul");
			var h = u.attr("eh");
			
			if (!toggleMessageExpanded(message)) { h = u.attr("ch"); }
				
			u.stop().animate({'height': h + 'px'}, 250);
			$(this).html(toggleMessage(message));
            						
            return false;
        });
    });
});
