$( document ).ready( function()
    {
        var adFenster = new Array();

        window.addEventListener("message", function(event)
            {
                if ( pageconfig['domain'] != event.origin )
                {
                    return;
                }
                console.log(event.data);
                var art = event.data['art'],
                    tan = event.data['tan'],
                    action = event.data['action'];
                
                if( 'adcheck' == action )
                {
                    console.log('okokok');
                    adFenster[art][tan]['opened'] = true;

                }
            }   
        );

        function checkAdOk( art, tan )
        {
            console.log('checkadok');
            if( false == adFenster[art][tan]['checked'] && false == adFenster[art][tan]['window'].closed )
            {
                var pdata = window.btoa(art) + '-' + window.btoa(tan)
                adFenster[art][tan]['checked'] = true;
                $.post( "ext/ap/ads.php",
                    {
                        'action': "checkAdOk",
                        'art': art,
                        'tan': tan
                    },
                    function(data, status)
                    {
                        window.open(pageconfig['domain']+'/adcheck.php?data='+pdata, art+'-'+tan, "height=120,width=200");
                    }
                );
            }
        }

        /*
        * if u do something wrong, sorry no matter which ad was active, invalidate 
        */
        function invalidateAd( art, tan )
        {
            console.log('invalidatead');
            adFenster[art][tan]['checked'] = true;
            var pdata = window.btoa(art) + '-' + window.btoa(tan)
            $.post( "ext/ap/ads.php",
                {
                    'action': "invalidateAd"
                },
                function(data, status)
                {
                    window.open(pageconfig['domain']+'/adcheck.php?data='+pdata, art+'-'+tan, "height=120,width=200");
                }
            );


        }

        async function startAdCountdown( art, tan, sec )
        {
            console.log('startadcountdown');
            let timer = setInterval( () =>
                {
                    console.log('checktimer');
                    if( true == adFenster[art][tan]['checked'] )
                    {
                        clearInterval(timer);
                    } else {
                        if( document.hasFocus() )
                        {
                            invalidateAd( art, tan );
                            clearInterval(timer);
                        }
                        if ( 'undefined' == adFenster[art][tan]['window'].closed || adFenster[art][tan]['window'].closed )
                        {
                            invalidateAd( art, tan );
                            clearInterval(timer);
                        }
                    }
                },
                100
            );
            await sleep(sec * 1000);
            checkAdOk( art, tan );
        }


        /*
        * communicates with ad window, placing detection of actual click
        */
        function openAdWindow( art, tan, sec )
        {
            if ( 'undefined' == typeof adFenster[art] || (! adFenster[art] instanceof Array ) )
            {
                adFenster[art] = new Array();
            }

            if ( 'undefined' == typeof adFenster[art][tan] || (! adFenster[art][tan] instanceof Array ) )
            {
                adFenster[art][tan] = new Array();
            }

            if( ( 'undefined' == adFenster[art][tan]['window'] || null == adFenster[art][tan]['window'] ) || adFenster[art][tan]['window'].closed )
            {
                var data = window.btoa(art) + '-' + window.btoa(tan);
                adFenster[art][tan]['window'] = window.open( pageconfig['domain'] + '/adclick.php?data='+data, "_blank" );

                adFenster[art][tan]['window'].focus();
                adFenster[art][tan]['opened'] = false;
                adFenster[art][tan]['checked']= false;
                console.log('meh');
                adFenster[art][tan]['window'].onbeforeunload = function()
                {   console.log('startadcountdowncall');
                    startAdCountdown( art, tan, sec );
                }
            }
        }


        /*
        * gets executed on click on ad
        */
        $( "#forcedbanner_display" ).on('click', function(e)
            {
                var elem = $( e.target ).closest( "li" );
                var sec = elem.data('sec');
                var tan = elem.data('tan');
                var art = elem.data('art');
                if (typeof tan !== typeof undefined && tan !== false)
                {
                    if (typeof art !== typeof undefined && art !== false)
                    {
                        if (typeof sec !== typeof undefined && sec !== false)
                        {
                            $(elem).remove();
                            openAdWindow( art, tan, sec );
                        }
                    }
                }
            }
        );

        /*
        * gets executed first, loads available ads and prepares the bootstrap <ul>-list for display
        */
        function loadAds( art )
        {
            $.post( "ext/ap/ads.php",
                {
                    'action': "getNewAdData",
                    'adArt' : art
                },
                function(data, status)
                {
                    var useData = jQuery.parseJSON( data );
                    if( 0 < useData.count )
                    {
                        $( "#forcedbanner_display" ).html('<ul class="list-group" id="forcedbanner_display_grp"></ul>');
                        $( "#forcedBannerTmpl_list" ).tmpl( useData.data ).appendTo( $( "#forcedbanner_display ul" ) );
                    }
                }
            );
        }

        $( "#loadAds_btn").on('click', function(e) { loadAds( 'forcedbanner' ) } );

        loadAds( 'forcedbanner' );
    }
);