;jQuery(document).ready(function($) {
    function basename(path) {
        return path.replace(/\\/g,'/').replace( /.*\//, '' );
    }

    function dirname(path) {
        return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');;
    }

    $('.hoverbuilding').each(function() {
        var hoverbuilding = $(this),
            img = null,
            baseURL = dirname(dirname($('#hoverbuilding-script').attr('src'))) + '/images/hoverbuilding';
    
        function buildURL(index) {
            return baseURL + '/hoverbuilding-' + index + '.png';
        }


        img = $('<img alt="Building layout diagram" width="407" height="169" />').attr('src', buildURL('base'));
        hoverbuilding.append(img);
        
        hoverbuilding.find('a').each(function() {
            var index = ($(this).data('hoverbuilding')),
                preloadImg = null;
            if (index != undefined) {
                preloadImg = $('<img/>').css({'width': 0, 'height': 0, 'position': 'absolute'}).attr('src', buildURL(index));
                $('body').append(preloadImg);
                preloadImg.load(function() {
                    $(this).remove();
                });
            }
        });

        hoverbuilding.find('a').hover(function() {
            var index = ($(this).data('hoverbuilding'));
            if (index != undefined) {
                img.prop('src', buildURL(index));
            }
        },
        function() {
            img.prop('src', buildURL('base'));
        });

    });
});

