$(document).ready(function() {

    /* advert images loading */
    $('.with-popup a[rev]').hover(function() {
        var params = parseQuery($(this).attr('rev'));
        
        // vlozim popup reklamny obrazok, a to len raz
        if ($(this).find('.popup-advert').length == 0) {
            $(this).prepend('<img class="popup-advert" src="' + params['link'] + '" alt="BANNER: pop-up reklama" width="' + params['width'] + '" height="' + params['height'] + '" />');
        }
    }, function() {});
                         
    /* advert images delayed show */
    $('.with-popup a[rev]').each(function() {
        $(this).hover(function() {
            calculatePosition($(this), $('.popup-advert', $(this)), $('img', $(this)).not('.popup-advert')); // parent, advert image, offset
            $(this).addClass('open');
        }, function() {
            $(this).removeClass('open');
        });
    });
   
});


// pocitanie suradnic umiestnenia popup reklamy
function calculatePosition(par, adv, off) {
    var advWidth, advHeight, sTop, winWidth, winHeight, offTop, offLeft, offWidth, offHeight, posX, posY, parTop, parLeft, parWidth;

    // parent
    parTop    = par.offset().top;
    parLeft   = par.offset().left;
    parWidth  = par.width();

    // advert
    advWidth  = adv.width();
    advHeight = adv.height();

    // offset image
    offTop    = off.position().top;
    offLeft   = off.position().left;
    offWidth  = off.width();
    offHeight = off.height();

    // viewport
    winWidth  = $(window).width();
    winHeight = $(window).height();
    sTop      = $(document).scrollTop();

    posX      = offLeft - advWidth;
    posY      = (offTop + offHeight) - advHeight;
    // posY      = (offTop + (offHeight / 2)) - (advHeight / 2);

    if (parTop + posY + advHeight > sTop + winHeight) {
        if (advHeight >= winHeight) {
            adv.css({left: (posX) + 'px', top: (sTop) + 'px'});
        } else {
            adv.css({left: (posX) + 'px', top: + (offTop - (advHeight - (winHeight - parTop + sTop))) + 'px'});
        }
    } else {
        adv.css({left: (posX) + 'px', top: (posY) + 'px'});
    }
}

// parse parameters
function parseQuery(query) {
    var Params = new Object();

    if (!query) {
        return Params;
    }

    var Pairs = query.split(/[;&]/);

    for (var i = 0; i < Pairs.length; i++) {
        var KeyVal = Pairs[i].split('=');

        if (!KeyVal || KeyVal.length != 2) {
            continue;
        }

        var key = unescape( KeyVal[0] );
        var val = unescape( KeyVal[1] );
            val = val.replace(/\+/g, ' ');

        Params[key] = val;
    }

    return Params;
}

