
$(document).ready(function() {

    $.address.init(function() {

        $(".tab a").click(function() {
            $.address.value($(this).attr("href"));
            return false;
        });

        $(".usingoursite .item").click(function() {
            $.address.value($(this).attr("href"));
            return false;
        });

    }).change(function() {

        var pathNames = $.address.pathNames();
        var navItem;

        if (pathNames.length == 0) {
            navItem = $(".tab a[rel=buying-online]");
        } else {
            navItem = $(".tab a[href='/" + pathNames[0] + "']");
        }

        $(".tab a.selected").removeClass("selected");
        navItem.addClass("selected");

        var contentBlockId = "content-" + navItem.attr("rel");
        var currentContentBlock = $(".contentblock:not(:hidden)");

        if (currentContentBlock.attr("id") != contentBlockId) {
            $(".contentblock:not(:hidden)").fadeOut(function() {
                $("#" + contentBlockId).fadeIn(function() {
                   loadSubContent($(this), pathNames);
                });
            });
        } else {
           loadSubContent(currentContentBlock, pathNames);
        }

        loadRightColumn(pathNames);

    });

});

function loadSubContent(contentContainer, pathNames, selectorPrefix)
{
    if (selectorPrefix == undefined) selectorPrefix = "#content-";

    var hasSubContent = (contentContainer.find(".subcontentblock").length > 0) ? true : false;
	if (pathNames.length > 1 && hasSubContent) {

        var subPath = pathNames[pathNames.length - 1];

        $(".item", contentContainer).removeClass("selected");
        $("a[rel=" + subPath + "]").addClass("selected");

        $(".subcontentblock:not(:hidden)", contentContainer).fadeOut(function() {
            $(selectorPrefix + subPath).fadeIn();
        });
    }
}

function loadRightColumn(pathNames)
{
    var rightColContainer = $("#rightcontent");

    if (pathNames.length > 0) {

        var path = pathNames[0];

        $(".subcontentblock:not(:hidden)", rightColContainer).fadeOut(function() {
            $("#rightcol-" + path).fadeIn();
        });
    }
}