﻿(function($) {
    var context, sticky, meta, link, target;
    var fadeDuration = 1000;

    mouseover = function(e) {
        var newMeta = $(this).attr('meta');
        //console.log('mouseover ' + newMeta);
        if (newMeta == '')
            sticky = true;
        else {
            link = $(this).attr('href');
            target = $(this).attr('target');
            myFade(newMeta, 1, fadeDuration);
            if (sticky) {
                sticky = false;
                myFade(meta, 0, fadeDuration);
            }
            meta = newMeta;
        }
        //console.log('sticky = ' + sticky);
    }

    mouseout = function(e) {
        var outMeta = $(this).attr('meta');
        //console.log('mouseout ' + outMeta);
        window.setTimeout(function() {
            if (!sticky) {
                myFade(outMeta, 0, fadeDuration);
            }
        }, 50);
    }

    click = function(e) {
        var w = target == '_blank' ? window.open('', '_blank') : window;
        w.location.href = link;
        e.preventDefault();
        //console.log(link);
    }

    myFade = function(meta, opacity, duration) {
        var img = context.find('img[meta="' + meta + '"]');
        if (img.is(':animated'))
            img.stop();
        img.fadeTo(duration, opacity);
        //console.log('fade ' + meta + ' to ' + opacity);
    }

    $.fn.aocfrontpage = function() {
        // Save the element that the plug-in is attached to
        context = $(this);
        // Hide all applicable images, except the last one
        context.find('img[meta]').filter(':not(:last)').fadeTo(0, 0).css('z-index', '100');
        // Save the last image as the one to display when the mouse is not over a hotspot
        defaultMeta = context.find('img[meta]').filter(':last').attr('meta');
        // Find the image map
        var map = $(this).find('map:first');
        // Hookup event handlers for each area
        map.find('area').hover(mouseover, mouseout);
        map.find('area').click(click);

    };


})(jQuery);
