/**
 * Minified by jsDelivr using Terser v3.14.1.
 */
!function(e){var n;if("function"==typeof define&&define.amd&&(define(e),n=!0),"object"==typeof exports&&(module.exports=e(),n=!0),!n){var t=window.Cookies,o=window.Cookies=e();o.noConflict=function(){return window.Cookies=t,o}}}(function(){function e(){for(var e=0,n={};e<arguments.length;e++){var t=arguments[e];for(var o in t)n[o]=t[o]}return n}function n(e){return e.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function t(o){function r(){}function i(n,t,i){if("undefined"!=typeof document){"number"==typeof(i=e({path:"/"},r.defaults,i)).expires&&(i.expires=new Date(1*new Date+864e5*i.expires)),i.expires=i.expires?i.expires.toUTCString():"";try{var c=JSON.stringify(t);/^[\{\[]/.test(c)&&(t=c)}catch(e){}t=o.write?o.write(t,n):encodeURIComponent(String(t)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var f="";for(var u in i)i[u]&&(f+="; "+u,!0!==i[u]&&(f+="="+i[u].split(";")[0]));return document.cookie=n+"="+t+f}}function c(e,t){if("undefined"!=typeof document){for(var r={},i=document.cookie?document.cookie.split("; "):[],c=0;c<i.length;c++){var f=i[c].split("="),u=f.slice(1).join("=");t||'"'!==u.charAt(0)||(u=u.slice(1,-1));try{var a=n(f[0]);if(u=(o.read||o)(u,a)||n(u),t)try{u=JSON.parse(u)}catch(e){}if(r[a]=u,e===a)break}catch(e){}}return e?r[e]:r}}return r.set=i,r.get=function(e){return c(e,!1)},r.getJSON=function(e){return c(e,!0)},r.remove=function(n,t){i(n,"",e(t,{expires:-1}))},r.defaults={},r.withConverter=t,r}(function(){})});

/**
 * Reverse
 * https://stackoverflow.com/a/5386150/585626
 */
jQuery.fn.reverse = [].reverse;
/**
 * Window ON > LOAD
 */
$( window ).on( "load", function() {
	var pageURI = document.location.href;
	var screen_width = $(window).width();
	var screen_height = $(window).height();
	var protocol = location.protocol.replace(':','');
	var url = pageURI.replace(protocol+'://'+window.location.hostname+'/', '');
	var type = $("body").attr( "data-page" );
	var theme_url = $("body").attr( "data-theme-url" );
	
	console.info("Page: "+type+" Screen: "+screen_width+'x'+screen_height);
	
	// Click to href=# and scroll
	$(document).on('click', 'a[href^="#"]', function(e) {
		// target element id
		var id = $(this).attr('href');
        if (id.length<2) return;
        
		// target element
		var $id = $(id);
		if ($id.length === 0) {
			return;
		}
	
		// prevent standard hash navigation (avoid blinking in IE)
		e.preventDefault();
	
		// top position relative to the document
		var pos = $id.offset().top;
	
		// animated top scrolling
		$('body, html').animate({scrollTop: pos});
		$( $id ).removeClass('item-highlight').addClass('item-highlight');
	});

	// GamePlay Responsive Layout
	if (type == 'single') {
        var gameTitle = $('img#gi').attr('alt');
        var slug = $("body").attr( "data-slug" );
        var ID = $("body").attr( "data-ID" );
		var image = $('img#gi').attr('src');

        // Screen Overflow
		if ( $("#gamebox").height() > screen_height ) {
			$("#gamebox").height(screen_height);
			console.log("#gamebox height>screen_height");
        }
        if ( $("#gamebox").width() > screen_width ) {
			$("#gamebox").width(screen_width);
			console.log("#gamebox width>screen_width");
		}

		console.log( '#game height:' + $("#game").height() );
		console.log( '#game .embed height:' + $("#game > .embed").height() );
        console.log( "image : "+ image );
        
		if ( $("#game").height() > $("#game > .embed").height()+250 ) {
			console.log("Small Screen Detected...");
			$("#game").addClass("full");
		}
        
		// Responsive ADS > Game Side
		console.log('game_w:'+game_w);
		console.log('#game.width()'+$('#game').width());
		
		if ( $('#game > .embed').width() < game_w ) $('#game > .ad.L').hide();
		if ( $('#game > .embed').width() < game_w ) $('#game > .embed').css('margin-left', 0);
		
		if ( $('#game > .embed').width() < game_w ) {
			$('#game > .ad.R').hide();
			$('#game > .embed').css({"margin": 0, "display": "block", "flex": "100%"});
        }

		// Add to History (cookie)
        var history = Cookies.get('history');
		if (history) {
			var parsed = JSON.parse(history);
			parsed[ ID ] = {"title":gameTitle, "url": url, "image": image};		
			Cookies.set('history', JSON.stringify(parsed), { expires: 365 });
		} else {
			var new_list = {};
			new_list[ ID ] = {"title":gameTitle, "url": url, "image": image};
			Cookies.set('history', new_list, { expires: 365 } );
		}
		
        // GPDR for Gamedist
		var cookieconsent_status = Cookies.get('cookieconsent_status');
		console.log("cookieconsent_status:" + cookieconsent_status);
		var iframe = $('#gamebox');

		// iFrame Exists and frame src contains "gamedistribution"
		if( iframe.length && iframe.attr('data-src').indexOf('gamedistribution') > -1 ) {
			var src = iframe.attr('data-src');
			var qq = '?';

			if (src.includes("?")) qq = '&';
			if ( cookieconsent_status == "allow" )
				iframe.attr('data-src', src+qq+'gdpr-tracking=1&gdpr-targeting=1&gdpr-third-party=1');
			else
				iframe.attr('data-src', src+qq+'?gdpr-tracking=0&gdpr-targeting=0&gdpr-third-party=0');
		}

		// cookieconsent loader
		if ( cookieconsent_status != "allow" ) {
			$.get("/?cookieconsent=1 body", function(data) {
				$("body").append(data);
            });
		}

		// Start Game
		$("#start").click(function() {
			console.log("Start Clicked");
			if ($("body").hasClass('ad-blocker')) {
				console.log("AdBlock Detected");
				$(".starter *").hide();
				$(".starter img").show().attr('src', theme_url + '/assets/images/adBlock.gif');
				$(".starter img").click(function() {
					location.reload();
				});
			} else {
				// Hide Start Game Screen
				$(".starter").slideUp("fast", function() {
					// Show the Game Frame
					$("#gamebox").attr('src',$("#gamebox").attr('data-src')).slideDown("slow", function() {
						// Slide to Game Element
						$('html, body').animate({
							scrollTop: $("#gamebox").offset().top
						});

						// Active Fullscreen Button
						$("#FS .passive").removeClass('passive');
					});
				});
			}
		});

		// More Tags action
		$(".more-tags").click(function() {
			console.log("More Clicked");
			$(this).html ( $(this).find('span').html() ).removeClass();
		});


	} // end SINGLE 

	// Search
	$("#top-nav li.search").click(function() {
		$("#toggle").attr("data-set", "search");

		if ($(this).hasClass('active')) {
			$(this).removeClass('active');
			$("#toggle").slideUp();
		} else {
			$(".active").removeClass('active');
			$(this).addClass('active');
			$("#tc").slideUp();
			$( "#toggle" ).slideDown( "fast", function() {
				$( "#toggle" ).load( "/?search-box=1" );
			});
		}
	});

	// Share
	$("#share").click(function() {
		$("#toggle").attr("data-set", "search");

		if ($(this).hasClass('active')) {
			$(this).removeClass('active');
			$("#toggle").slideUp();
		} else {
			$(".active").removeClass('active');
			$(this).addClass('active');
			$( "#toggle" ).slideDown( "fast", function() {
				$( "#toggle" ).load( "/?share=1" );
			});
		}
	});

    // History
    $("#top-nav li.history").click(function() {
        $("#toggle").attr("data-set", "history");
        var history = Cookies.get('history');
        if (history) {
            echo_cookie( history, "#toggle" );
            if ($(this).hasClass('active')) {
                $(this).removeClass('active');
                $("#toggle").slideUp();
            } else {
                $(".active").removeClass('active');
                $(this).addClass('active');
                $("#toggle").slideDown();
                $("#tc").slideUp();
            }
        } else {
            console.log('History: Empty!');
            $(this).addClass('passive');
            $("#toggle").hide();
        }
        

    });

	// Categories - Menu toggle
	$("li.categories").click(function() {

		if ($(this).hasClass('active')) {
			$(this).removeClass('active');
			$("#tc").slideUp();
		} else {
			$(".active").removeClass('active');
			$(this).addClass('active');
			$("#toggle").hide();
			$("#tc").slideDown();
		}

	});
	
	// Favorites
    var liked = Cookies.get('liked');
    if ( liked ) {
		var parsed = JSON.parse(liked);
        // Before Liked
		if (type == 'single' && parsed.hasOwnProperty(ID)) {
			console.log("Before Liked:"+ID);
			$("#fav").addClass('liked');
		}
		
		// Liked games count
		var liked_count = echo_cookie(liked, 'NONE', 6, "s", false);
		if (liked_count>9) liked_count = '9+';
		if (liked_count) $("header .menu li.liked .c").text(liked_count).delay(3000).fadeIn('slow');
	}

		// Favorites toggle
		$("li.favorite").click(function() {
            var liked = Cookies.get('liked');
			if (liked) {
				$("#toggle").attr("data-set", "liked");
				
				echo_cookie( liked, "#toggle" );
				if ($(this).hasClass('active')) {
					$(this).removeClass('active');
					$("#toggle").slideUp();
				} else {
					$(".active").removeClass('active');
					$(this).addClass('active');
					$("#toggle").slideDown();
					$("#tc").slideUp();
				}
			} else {
                console.log('Favs are Empty!');
                $(this).addClass('passive');
                $("#toggle").slideDown();
				$("#tc").slideUp();
				$("#fav").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
			}

        });
        
		// Click to Like
		$("#fav").click(function() {
            $("#toggle").hide();
            /*
			var ls = $('header li.liked .c');
			var lc = parseInt(ls.text());
			$("#header li.favorite").addClass("item-highlight").delay(2000).queue(function(next){
				$(this).removeClass("item-highlight");
				next();
            });
            */
			// Unlike
			if ( $(this).hasClass("liked") ) {
                // Menu Numbers
                /*
				if (lc <= 1) ls.text('0');
				else ls.text( lc-1 );
                */
				// Unlike Action
				$('#fav').removeClass("liked");

                var parsed = JSON.parse(liked);
				// remove in array
				delete parsed[ID];
				// Count
				var size = Object.keys(parsed).length;
				if ( size ) {
					// Obect to JSON
					var json_data = JSON.stringify(parsed);
					// set cookie
					Cookies.set('liked', json_data, { expires: 365 });
				} else {
					Cookies.remove('liked');
				}
				return;
			}
			// Like IT
			$('#fav').addClass("liked");
	
			// Menu action
			//drag_to_like ();
    
            /*
			if (lc != '9+' ) {
				if ( lc == '' ) lc = 0;
				if (lc>9) ls.text('9+');
					else ls.text(lc + 1);
			}
            */
			if (liked) {
				var parsed = JSON.parse(liked);
				parsed[ ID ] = {"title":gameTitle, "url": url, "image": image};
				// Obect to JSON
				var json_data = JSON.stringify(parsed);
				// set cookie			
				Cookies.set('liked', json_data, { expires: 365 });
			} else {
				var addpage = {};
				addpage[ slug ] = {"title":gameTitle, "url": url, "image": image};
				Cookies.set('liked', addpage, { expires: 365 } );
			}
		});

	// Header - Responsive
	var mt = $("#header #mt");
	var logo = $("#header .logo img");
	var maxheight = 55;
	if(logo.length != 0) maxheight = logo.height();
	
	/*
	if ( mt.height() > maxheight ) {
		mt.addClass('only-icons');
	}
	*/

	$('#header #mt li a').reverse().each(function () {

		$(this).css('white-space', 'nowrap');
		var nowrapHeight = $(this).height();

		$(this).css('white-space', 'normal');
		var normalwrapHeight = $(this).height();

		if ( nowrapHeight < normalwrapHeight ) {
			if ( $(this).find('svg, i, img').length )
				$(this).addClass("only-icon");
			else
				$(this).parent().hide();
		}
	});



	// Click Hamburger Menu
	$("header .th").click(function() {
		$("header .menu").addClass("th");
		$(".th-hide").show();
		$(".logo").hide();
	});
	$("header .menu .th-hide").click(function() {
		$("header .menu").removeClass("th");
		$(".th-hide").hide();
		$(".logo").show();
	});
});

/*
Show Cookie
*/
function echo_cookie( json, target, count = 0, echo = true ) {
	if ( ! json ) return 0;
	var i = 0;
	var parsed = JSON.parse(json);	
    if (echo) $( target ).html('');
    $( target ).append('<div class="w gtc ec"></div>');

	for(var ID in parsed){
        console.log("echo_cookie:"+ID);
		if ( (i<count || count == 0) && echo ) {			
			$( target+ ' .ec' ).append('<div data-cid="'+ID+'" class="btn btn-colored btn-green"><a href="javascript:remove_cookie(\''+ID+'\', \''+$( target ).attr('data-set')+'\');" class="x"><i class="fas fa-times-circle"></i> '+__REMOVE+'</a><a href="/'+parsed[ID]['url']+'"><img src="'+parsed[ID]['image']+'"><span class="title">'+parsed[ID]['title']+'</span></a></div>');
		}
		i++;
	}
	return i;
}


/*
toggle -> remove_cookie
*/
function remove_cookie ( cookieID = null, cookieSet = null ) {
	console.log("Remove X -> Clicked");
	
	
	var wrapper = $("div[data-cid='"+cookieID+"']");

	console.log("removed cookieID: "+cookieID);
	console.log("cookieSet: "+cookieSet);

	
	wrapper.addClass("item-highlight").delay(100).queue(function(next){
		$(this).fadeOut();
		wrapper.fadeOut("slow");
		next();
	});

	var cookies = JSON.parse(Cookies.get(cookieSet));
	delete cookies[cookieID]; // remove in array

	if ( Object.keys(cookies).length ) {
		Cookies.set(cookieSet, JSON.stringify(cookies), { expires: 365 });
	} else {
		Cookies.remove(cookieSet);
	}
}

/* drag_to_like */
function drag_to_like () {
	var cart = $('header .menu li.favorite');
	var imgtodrag = $('#gi');
	if (imgtodrag) {
		var imgclone = imgtodrag.clone()
			.offset({
			top: imgtodrag.offset().top,
			left: imgtodrag.offset().left
		})
			.css({
			'opacity': '0.8',
				'position': 'absolute',
				'height': '100px',
				'width': '160px',
				'z-index': '100'
		})
			.appendTo($('body'))
			.animate({
			'top': cart.offset().top + 1,
				'left': cart.offset().left + 1,
				'width': 70,
				'height': 60
		}, 3000, 'easeInOutExpo');
		
		imgclone.animate({
			'width': 0,
			'height': 0
		}, function () {
			$(this).detach()
		});
	}
}


// Re-load button Action
$('#refresh').click(function() {
	if($('#gamebox').length){
		var iframe = document.querySelector('#gamebox');
		var game_src = iframe.src;
		iframe.src = '#';
		iframe.src = game_src;
	}
});

/**
 * FullScreen API
 * https://codepen.io/ssk7833/pen/mVOXXp
 */
function requestFullScreen() {
	if (document.fullscreenEnabled) {
		// Your browser supports fullscreen
		fullscreen();
		return true;
	} else {
		// Your browser cannot use fullscreen right now
		return false;
	}
}
  
function fullscreen() {
// check if fullscreen mode is available
if (document.fullscreenEnabled || 
	document.webkitFullscreenEnabled || 
	document.mozFullScreenEnabled ||
	document.msFullscreenEnabled) {
	
	// which element will be fullscreen
	var iframe = document.querySelector("#gamebox");

	// Do fullscreen
	if (iframe.requestFullscreen) {
	iframe.requestFullscreen();
	} else if (iframe.webkitRequestFullscreen) {
	iframe.webkitRequestFullscreen();
	} else if (iframe.mozRequestFullScreen) {
	iframe.mozRequestFullScreen();
	} else if (iframe.msRequestFullscreen) {
	iframe.msRequestFullscreen();
	}
	
}
else {
	document.querySelector('.error').innerHTML = 'Your browser is not supported Full screen';
}
}
  
var FS = document.querySelector('#FS');
if(FS) FS.addEventListener('click', requestFullScreen);

// when you are in fullscreen, ESC and F11 may not be trigger by keydown listener. 
// so don't use it to detect exit fullscreen
/*
document.addEventListener('keydown', function (e) {
console.log('key press' + e.keyCode);
});
*/