/**
 * javascript logic for the inskin-enabled smart-sizing game page
 *
 * There are about 30 possible code paths to generate the game page. To make sense of this,
 * you'll have a much better time if you have the flowchart with you.
 *
 * This code has been deliberately broken into lots of little functions, to closely match
 * the flowchart. Otherwise, this could devolve into lots of lots of nested IF's ...
 *
 */
// default inskin params
var inskinTop = 60;
var inskinSide = 30;
var inskinBottom = 40;

if(typeof InSkinParams=="undefined") InSkinParams={};

InSkinParams['myInSkin1'] = {
    'srv_Keywords': '',
    'plr_AdCallMap': {
        '1': {
            'srv_SectionID': 000000,
            'srv_Keywords': gameUniqueName + ',' + gameTags,
            'requireNoPreroll': true,
            'fallbackWhenNoSkin': true
        }
    },
    'plr_TotalW': 900,
    'plr_TotalH': 600,
    'srv_Categories': gameTags,
    'srv_UseSAS': 'false',
    'srv_PauseAdTag': "<script language=\"javascript\">\r\n<!--\r\nif (window.adgroupid == undefined) {\r\n        window.adgroupid = Math.round(Math.random() * 1000);\r\n}\r\ndocument.write('<scr'+'ipt language=\"javascript1.1\" src=\"http:\/\/adserver.adtech.de\/addyn|3.0|656.1|1684858|0|16|ADTECH;cookie=info;loc=100;target=_blank;key='   gameUniqueName   ';grp='+window.adgroupid+';misc='+new Date().getTime()+'\"><\/scri'+'pt>');\r\n\/\/-->\r\n<\/script>\r\n\r\n<script language=\"javascript\">\r\n<!--\r\nif (window.adgroupid == undefined) {\r\n        window.adgroupid = Math.round(Math.random() * 1000);\r\n}\r\ndocument.write('<scr'+'ipt language=\"javascript1.1\" src=\"http:\/\/adserver.adtech.de\/addyn|3.0|656.1|1683854|0|16|ADTECH;cookie=info;loc=100;target=_blank;key='   gameUniqueName   ';grp='+window.adgroupid+';misc='+new Date().getTime()+'\"><\/scri'+'pt>');\r\n\/\/-->\r\n<\/script>",
    'plr_InSkinID': 'myInSkin1',
    'plr_ContentID': gameUniqueName,
    'plr_FrameTop': inskinTop,
    'plr_FrameSide': inskinSide,
    'plr_FrameBottom': inskinBottom,
    'plr_ContentType': 'IPCGAME',
    'plr_ExpandableDetached': true,
    'plr_NoSkinContentResize': true,
    'plr_NoSkinInSkinResize': true,
    'plr_SetMask': false,
    'cnt_IsPlaying': true
}

var applifierHeight = 95; //108;
if ($("#applifier_ad").length == 0) 
    applifierHeight = 0;

// CORE LOGIC
if (gameMediaType == 'shockwave') {
    // do nothing   
}
else {
    if (gameInskinEnabled) {
        detectScreenResolution();
    }
    else {
        detectPrerollEnabled();
    }
}


function detectScreenResolution(){
    if (screen.width >= 1024) {
    
        if (screen.width >= 1024 && screen.width < 1280) {
            InSkinParams.myInSkin1['srv_SectionID'] = '124004';
            InSkinParams.myInSkin1.plr_AdCallMap[1].srv_SectionID = '124143'; // Med Res i-Roll ID
            InSkinParams.myInSkin1['plr_InSkinW'] = InSkinParams.myInSkin1['plr_NoSkinContentW'] = 790;
            InSkinParams.myInSkin1['plr_InSkinH'] = InSkinParams.myInSkin1['plr_NoSkinContentH'] = 800;
        }
        else 
            if (screen.width >= 1280) {
                InSkinParams.myInSkin1['srv_SectionID'] = '124003';
                InSkinParams.myInSkin1.plr_AdCallMap[1].srv_SectionID = '124142'; // Hi Res i-Roll ID
                InSkinParams.myInSkin1['plr_InSkinW'] = InSkinParams.myInSkin1['plr_NoSkinContentW'] = 1044;
                InSkinParams.myInSkin1['plr_InSkinH'] = InSkinParams.myInSkin1['plr_NoSkinContentH'] = 800;
            }
        
        InSkinParams.myInSkin1['srv_Keywords'] = gameUniqueName + ',' + gameTags;
        
        // content area size
        InSkinParams.myInSkin1['plr_NoSkinContentW'] = InSkinParams.myInSkin1['plr_ContentW'] = InSkinParams.myInSkin1['plr_InSkinW'] - 2 * inskinSide;
        InSkinParams.myInSkin1['plr_NoSkinContentH'] = InSkinParams.myInSkin1['plr_ContentH'] = InSkinParams.myInSkin1['plr_InSkinH'] - inskinTop - inskinBottom;
        
        console.log('game width ' + gameWidth + ' and height ' + gameHeight);
        console.log('content width ' + InSkinParams.myInSkin1['plr_ContentW'] + ' and height ' + InSkinParams.myInSkin1['plr_ContentH']);
        // does the game fit in content area?
        if (gameWidth <= InSkinParams.myInSkin1['plr_ContentW'] && gameHeight <= InSkinParams.myInSkin1['plr_ContentH']) {
            //--- if (gameWidth <= InSkinParams.myInSkin1['plr_ContentW'] && (gameHeight+applifierHeight) <= InSkinParams.myInSkin1['plr_ContentH']){
            console.log('game fits in inskin content area');
            detectGameScalableForInskin();
        }
        else {
            console.log('game DOES NOT fit in inskin content area');
            detectPrerollEnabled();
        }
    }
    else {
        detectPrerollEnabled();
    }
}


function detectGameScalableForInskin(){
    if (!gameIsScalable) {
        console.log('game not scalable for inskin');
        embedGameAtNativeSizeWithInskin();
    }
    else {
        console.log('game scalable for inskin');
        embedUpscaledGameInInskinContentArea();
    }
}

function detectGameScalableNoInskin(){
    if (!gameIsScalable) {
        embedGameAtNativeSize();
    }
    else {
        embedUpscaledGameWithoutInskin();
    }
}


function detectPrerollEnabled(){
    console.log('detecting preroll ' + usePreroll);
    
    if (usePreroll) {
        console.log('showing preroll');
        embedPreroll();
    }
    else {
        detectGameScalableNoInskin();
    }
    
    
}

function embedUpscaledGameInInskinContentArea(){
    // upscale the game within the inskin content area (but no taller than the viewport)
    var swfScaleFactorToSuitInskin = Math.min(InSkinParams.myInSkin1['plr_ContentW'] / gameWidth, InSkinParams.myInSkin1['plr_ContentH'] / gameHeight)
    var swfScaleFactorToSuitViewport = Math.min($('#tab-game').width() / gameWidth, ($(window).height()) / gameHeight);
    
    console.log('original size ' + gameWidth + ' ' + gameHeight);
    console.log('swfScaleFactorToSuitInskin ' + swfScaleFactorToSuitInskin);
    console.log('swfScaleFactorToSuitViewport ' + swfScaleFactorToSuitViewport);
    var swfScaleFactor = Math.min(swfScaleFactorToSuitInskin, swfScaleFactorToSuitViewport);
    swfScaleFactor = Math.max(swfScaleFactor, 1);
    console.log("swfScaleFactor " + swfScaleFactor);
    swfScaledWidth = swfScaleFactor * gameWidth;
    swfScaledHeight = swfScaleFactor * gameHeight;
    console.log("swfScaledWidth " + swfScaledWidth + ' ' + ' swfScaledHeight ' + swfScaledHeight);
    embedGame(swfScaledWidth, swfScaledHeight);
    makeInskinRequest();
}

function embedGameAtNativeSizeWithInskin(){
    console.log('embedGameAtNativeSizeWithInskin');
    embedGame(gameWidth, gameHeight);
    makeInskinRequest();
}

function embedGameAtNativeSize(){
    console.log("embedGameAtNativeSize");
    embedGame(gameWidth, gameHeight);
}

function embedPreroll(){
	if( gameUniqueName == 'blazingsquad') {
		console.log('blazingsquad!');
		var so = new SWFObject("/preroll_loader/vast_preroll.swf", gameUniqueName, $('#tab-game').width() - 40, $(window).height() - 100, "6", "#000000");
	    so.addParam("scale", "noScale");
	    so.addParam("allowscriptaccess", "always");
    	so.addParam("salign","lt");
	}else {
		
		console.log('NOT blazingsquad!');
		var so = new SWFObject("/preroll_loader/as2_preroll_cs5.swf", gameUniqueName, $('#tab-game').width() - 40, $(window).height() - 100, "6", "#000000");
		so.addParam("scale", "noScale");
	    so.addParam("allowscriptaccess", "always");
		so.addVariable("preRollXML", "http://adserver.adtech.de/addyn|3.0|656.1|2150765|0|16|ADTECH;key=" + gameUniqueName);
	}
    so.write("flashcontent");
}

function postPrerollCallback(){
    console.log('preroll complete');
    detectGameScalableNoInskin();
    loadLeaderboard();
}

function embedUpscaledGameWithoutInskin(){
    var maxSwfScaleFactor = Math.min($('#tab-game').width() / gameWidth, ($(window).height() - 100) / (gameHeight + applifierHeight));
    //console.log("Get min of... maxSwfScaleFactor width: " + ($('#tab-game').width() / gameWidth) +", maxSwfScaleFactor height: "+($(window).height()-100) / (gameHeight+applifierHeight) +"windowH: "+($(window).height()-100)+", gameH: "+(gameHeight+applifierHeight) );
    
    maxSwfScaleFactor = Math.max(maxSwfScaleFactor, 1);
    console.log("maxSwfScaleFactor " + maxSwfScaleFactor);
    maxScaledSwfWidth = maxSwfScaleFactor * gameWidth;
    maxScaledSwfHeight = maxSwfScaleFactor * gameHeight;
    console.log("maxScaledSwfWidth " + maxScaledSwfWidth + ' ' + ' maxScaledSwfHeight ' + maxScaledSwfHeight);
    embedGame(maxScaledSwfWidth, maxScaledSwfHeight);
    $('#tab-game').height(maxScaledSwfHeight + applifierHeight);
    
    window.setTimeout("$('html,body').animate({scrollTop: $('#tab-game').offset().top}, 1500)", 2000);
}

function makeInskinRequest(){
	if(typeof InSkin=="undefined") {
		console.log('inSkin script blocked!');
	}else {
		console.log('starting inskin embed');
		var myInSkin1 = new InSkin.Base('myInSkin1');
		myInSkin1.init();
	}
}

var embedWidth;
var embedHeight;

function embedGame(width, height){
	embedWidth=width;
	embedHeight=height;
	
    var so = new SWFObject("/games/" + gameUniqueName + "/" + gameMediaUri, gameUniqueName, width, height, "6", "#" + gameBgColor);
    so.addParam("scale", "exactfit");
    so.addParam("wmode", "window"); // Needed for some games that have a transparent bg
    so.addParam("allowscriptaccess", "always");
    
    so.addVariable("gameSWF", "/games/" + gameUniqueName + "/" + gameMediaUri);
    so.addVariable("id", "myContent1");
    so.addVariable("name", "myContent1");
    
    //if (!gameInskinCompatible) {
    //    so.addParam("class", "InSkinHide");
    //}
	
    // Reset wmode to transparent if login required/dialog overlay box is used - 11/03/11 -Pratomchai 
    if (loginRequiredForGame == true) {
        so.addParam("wmode", "transparent");
    }
    so.write("flashcontent");
}

function reEmbedGame() {
	embedGame(embedWidth,embedHeight);
}


/*
 * inskin callback event handler
 */
function setLayoutForInSkin(hasSkin){
    console.log('setLayoutForInSkin: ' + hasSkin);
    
    //console.log('1 eventName: ' + eventName);
    // no inskin? upsize the game if the game is scalable
    // If game is scalable
    if (gameIsScalable) {
    
        // figure out the maximum size of the game if no inskin
        if (!hasSkin) {
            var maxSwfScaleFactor = Math.min($('#tab-game').width() / gameWidth, ($(window).height() - 100) / gameHeight);
            console.log('maxSwfScaleFactor 1: ' + maxSwfScaleFactor);
        }
        else {
            var useWidth = 730
            if (screen.width > 1024) 
                useWidth = 984;
            //                  useWidth = $('#tab-game').width();
            
            console.log("useWidth: " + useWidth);
            var maxSwfScaleFactor = Math.min(useWidth / gameWidth, 700 / (gameHeight + 10)); // +10px to compansate for div#flashcontent embed {margin-top:10px}
            console.log("usewidth: " + useWidth + ", gameWidth: " + gameWidth);
            console.log("Get min of... width: " + (useWidth / gameWidth) + ", height: " + (700 / (gameHeight + 10)));
            console.log('maxSwfScaleFactor 2: ' + maxSwfScaleFactor);
        }
        
        maxSwfScaleFactor = Math.max(maxSwfScaleFactor, 1);
        maxScaledSwfWidth = maxSwfScaleFactor * gameWidth;
        maxScaledSwfHeight = maxSwfScaleFactor * gameHeight;
        
        $('#' + gameUniqueName).width(maxScaledSwfWidth);
        $('#' + gameUniqueName).height(maxScaledSwfHeight);
        
        var maxTabGameScaleFactor = Math.max($('#InSkinContainer_myInSkin1').height(), (maxScaledSwfHeight + applifierHeight));
        
        $('#tab-game').height(maxTabGameScaleFactor);
        console.log("upscaling game to " + maxScaledSwfWidth + ' ' + maxScaledSwfHeight);
        
        if (hasSkin) {
            // Scroll up to the top of #tab-game container
            window.setTimeout("$('html,body').animate({scrollTop: $('#tab-game').offset().top}, 1500)", 1500);
        }
    }
    
    // make the tab wider if it doesn't fit
    newTabWidth = Math.max($('#tab-game').width(), $('#InSkinContainer_myInSkin1').width() + 10);
    $('#gamepage_tabs').width(newTabWidth);
    
    $('#InSkinContentContainer_myInSkin1').css({ "position": "absolute", "z-index": 2 });

}

var inSkin_shown = false;
var inSkin_callCount = 0;
var leaderboard_shown = false;

/*
 * We make a maximum of two InSkin ad calls, the first for an i-Roll, and a
 * second only if an InSkin wasn't returned with the i-Roll.
 */
function InSkinEvent(id, eventName, eventParams){

    //console.log('InSkin Event: ' + eventName);
    
    switch (eventName) {
        case 'adCallResult':
            inSkin_callCount++;
            if (eventParams.hasSkin || inSkin_callCount > 1) {
                // No more InSkin calls, we now know if an InSkin was returned or not
                inSkin_shown = eventParams.hasSkin;
                setLayoutForInSkin(inSkin_shown);
                
                if (showLeaderboardAd && !inSkin_shown && !leaderboard_shown) 
                    loadLeaderboard();
                else 
                    if (inSkin_shown && leaderboard_shown) 
                        hideLeaderBoard();
            }
            break;
            
        case 'adCallError':
            setLayoutForInSkin(inSkin_shown);
            break;
            
        case 'adServed':
            if (eventParams.type == 'InSkin') {
            //hideLeaderBoard(); // Shoulnd't be necessary.
            }
            
        default:
            break;
    }
}

function hideLeaderBoard(){
    if ($("#leaderboard_ad").height() > 0) {
        $("#leaderboard_ad").animate({
            "height": "0px"
        });
        $('#tab-game').height(tab_game_height);
    }
}

var tab_game_height;
function loadLeaderboard(){
	console.log('loadLeaderboard...');
    googleLeaderboardAd.location = "/ad/format/leaderboard/adchannel/game-page/keywords/" + gameUniqueName + " " + gameCat + "?" + new Date().getTime(); // googleLeaderboardAd.location = "/games/leaderboardadajax/"+gameUniqueName+"/"+gameCat+"?"+new Date().getTime();
    $("#leaderboard_ad").show().animate({
        "height": "90px"
    }, function(){
    
        $("#googleLeaderboardAd").height("100%");
        
        if (gameInskinEnabled) {
        	console.log('gameInskinEnabled.. tab game height: '+$("#tab-game").height());
            //tab_game_height = $("#tab-game").height(); //+50;
        	tab_game_height = $("#flashcontent").height() + $("#googleLeaderboardAd").height();
            window.setTimeout("$('html,body').animate({scrollTop: $('#tab-game').offset().top}, 1500)", 2000);
        }
        else {
            //tab_game_height = $("#tab-game").height() + 50;	//$("#googleLeaderboardAd").height();
        	tab_game_height = $("#flashcontent").height() + $("#googleLeaderboardAd").height();
        }
        if (!gameIsScalable) {
            // Set the tab game container to fit only the ad and game (take out the blank space under the game 
            $('#tab-game').height(($("#googleLeaderboardAd").height() + $("#flashcontent").height())); //+ 50
        }
        // Set the tab game container to fit only the ad and game (take out the blank space under the game
//        tab_game_height = $("#flashcontent").height() + $("#googleLeaderboardAd").height();
        console.log('tab_game_height: ' + tab_game_height);
        $('#tab-game').height(tab_game_height);
        
        $('html,body').animate({
            scrollTop: $('#tab-game').offset().top
        }, 1500);
        
    });
    
    //  if( $('#twig_div').length > 0 )
    //      $('#twig_div').load('/ad/format/twig/adchannel/game-page/keywords/'+gameUniqueName+gameCat+'?'+new Date().getTime() );  
}

$(document).ready(function(){
    var waitForInSkinAd = 3000;
    if (gameInskinEnabled == 1) 
        waitForInSkinAd = 6000;
    window.setTimeout(function(){
        if (inSkin_shown) {
            console.log('Doc Ready, inSkin_shown TRUE');
        }
        else {
            console.log('Doc Ready, inSkin_shown FALSE');
            
            //if( $("#leaderboard_ad").length > 0 && showLeaderboardAd ) {
            // If InSkin call has failed (callcount is 0) then load the
            // leaderboard.  Otherwise InSkin will load it once it has finished
            // all its calls if there's no InSkin format ad available
            if (showLeaderboardAd && inSkin_callCount == 0) {
           //     leaderboard_shown = true;
           //     loadLeaderboard();
            }
        }
    }, waitForInSkinAd);
    
/*
    window.setTimeout(function(){
    	var allAdsServed = true;
    	// Lets loop through all .img_ad elements...
    	$('.img_ad').each(function() {
    		//console.log('id: '+ $(this).attr('id'));
			//console.log('height: ' + $(this).height());
    		if($(this).height() < '30') {
    			allAdsServed = false;
    		}
    	});
    	if( !allAdsServed ) {
    		console.log('Not All ads served - PossibleAdBlocked!');
    		s.tl(this,'o','MB:Gamepage:PossibleAdBlocked:'+gameUniqueName);
    		//alert( 'Not All ads served!' );
    	}else{
    		console.log('All ads served!');
    		//alert( 'All ads served!' );
    	}
    }, 10000);	// Wait for 10 seconds to give the ads the change to load
*/
});

function loadGlobalScoresPage(pagenum){
    $('#gamepage_tabs').tabs('url', 2, '/games/' + gameUniqueName + '/scores/ajax/' + pagenum);
    $('#gamepage_tabs').tabs('load', 2);
}

/**
 * Function to manually get/check for submitting game score Elegibility
 */
//var submitScore = null;   // Global var
var uRegTracker = '1';
function getGameCredentials(score){
    //submitscore = false;
    console.log('getGameCredentials(score: ' + score + ');');
    
    FB.getLoginStatus(function(response){
        if (response.session) {
            // logged in and connected user
            console.log('getGameCredentials... Logged in');
            
            // For some reason, FB's response doesn't return permissions here so have to do a FQL
            var query = FB.Data.query('select name, email, first_name from user where uid={0}', response.session.uid);
            query.wait(function(rows){
                if (rows[0].email != null) {
                    //console.log('Have Email: '+rows[0].email);
                    if (score) {
                        submitScore = true;
                    }
                    //sendGameCredentials(rows[0].email, submitScore);
                    sendGameCredentials(rows[0].first_name, submitScore);
                }
                else {
                    console.log('Dont have Email! Show permissions box...');
                    if (score) {
                        submitScore = true;
                        $('#permissions-required-box .game-score').html(score);
                        $('#permissions-required-box .game-score-container').show();
                        //--$('#permissions-required-box').dialog('open');
                    }
                    //showPermissionRequired(submitScore);
                    showDialog('permissions', submitScore);
                }
            });
            
        }
        else {
        
            console.log('Show login-required-box...');
            if (score) {
                submitScore = true;
                $('#login-required-box .game-score').html(score);
                $('#login-required-box .game-score-container').show();
                //--$('#login-required-box').dialog('open');
            }
            //showLoginRequired(submitScore);
            showDialog('login', submitScore);
        }
    });
}

function doFBGameLogin(){
    FB.login(function(response){
        if (response.session) {
            console.log('logged in... check perms...');
            if (response.perms) {
                // user is logged in and granted some permissions.
                got_perms = true;
                //console.log('doFBGameLogin() Logged in and has new permissions (NEW OR OLD USER WITH NEW PERMS?!?)');
                //console.log('GOOGLE ANALYTICS: Controlled in doLogEmail()...');
                if (mymblocater == 'initGame') {
                }
                //mymbLogin();
            }
            else {
                // user is logged in, but did not grant any permissions
                //console.log('doLogin() Logged in and not allowed permissions (OLD USER NOT ALLOWED NEW PERMS)');
                console.log('GOOGLE ANALYTICS: FBREG:OLD:NO ------ localPageTracker0._trackEvent("FBREG", "OLD", "NO", "PERMISSIONS");');
                localPageTracker0._trackEvent("FBREG", "OLD", "NO", "PERMISSIONS");
                sendGameCredentials('', true);
            }
            // ##### Should the user be logged in if he has no perms? #####
            mymbLogin();
        }
        else {
            // user is not logged in
            console.log('Login canceled');
            console.log('GOOGLE ANALYTICS: FBREG:X:NO:LOGIN');
            localPageTracker0._trackEvent("FBREG", "X", "NO", "LOGIN");
            sendGameCredentials('', true);
        }
    }, {
        perms: 'email'
    });
}

var dialogOpts = {
    autoOpen: false,
    modal: true,
    width: 520,
    resizable: false,
    zIndex: 55000,
    show: "slide",
    hide: "explode"
}
function initDialogs(){
    $.fx.speeds._default = 650;
    $("#login-required-box").dialog(dialogOpts);
    $("#permissions-required-box").dialog(dialogOpts);
    $("#regcomplete-box").dialog({
        autoOpen: false,
        modal: true,
        width: 520,
        resizable: false,
        zIndex: 55000,
        show: "explode",
        hide: "explode"
    });
}

function showDialog(for_box, submit_score){
    console.log('showDialog...');
    var box = '#' + for_box + '-required-box';
    if ($.cookie('MB_GamePermRequestShown') == null) {
        console.log('GamePermRequestShown == null, open dialog for for_box: ' + for_box + ', box: ' + box);
        setTimeout(function(){
            $(box).dialog('open');
        }, 600);
    }
    else {
        if (submit_score) {
            sendGameCredentials('', submit_score);
        }
    }
}

function showRegCompleteDialog(){
    console.log('showRegCompleteDialog!');
    $("#regcomplete-box").dialog("open");
}

/*
 function showLoginRequired(submit_score)
 {
 if( $.cookie('MB_GamePermRequestShown') == null ) {
 $('#login-required-box').dialog('open');
 }else {
 if(submit_score) { sendGameCredentials('', submit_score); }
 }
 }
 function showPermissionRequired(submit_score)
 {
 if( $.cookie('MB_GamePermRequestShown') == null ) {
 $('#permissions-required-box').dialog('open');
 }else {
 if(submit_score) { sendGameCredentials('', submit_score); }
 }
 }
 */
function showFBPermissions(){
    $("#permissions-required-box").dialog("close");
    FB.ui({
        method: "permissions.request",
        "perms": "email"
    }, function(response){
        if (response.perms != null && (response.perms.indexOf('email') != -1)) {
            got_perms = true;
            //console.log('Old User just given Ext. Perms!');
            console.log('GOOGLE ANALYTICS: [FBREG:OLD:YES:PERMISSIONS] ----- localPageTracker0._trackEvent("FBREG", "OLD", "YES", "PERMISSIONS");');
            localPageTracker0._trackEvent("FBREG", "OLD", "YES", "PERMISSIONS");
            showRegCompleteDialog();
        }
        else {
            console.log('GOOGLE ANALYTICS: [FBREG:OLD:NO:PERMISSIONS] ----- localPageTracker0._trackEvent("FBREG", "OLD", "NO", "PERMISSIONS");');
            localPageTracker0._trackEvent("FBREG", "OLD", "NO", "PERMISSIONS");
        }
        mymbLogin();
    });
}

function closeDialog(for_box){
    var box = '#' + for_box + '-required-box';
    var opt_in = '#opt_in-' + for_box + '-required';
    if ($(box + " .game-score-container").is(":hidden")) {
        sendGameCredentials('', false);
    }
    else {
        sendGameCredentials('', true);
    }
    console.log('GOOGLE ANALYTICS: [FBREG:X:NO:JUSTPLAY] ----- localPageTracker0._trackEvent("FBREG", "X", "NO", "JUSTPLAY");');
    localPageTracker0._trackEvent("FBREG", "X", "NO", "JUSTPLAY");
    if ($(opt_in).is(':checked')) {
        $.cookie('MB_GamePermRequestShown', maxDelayForPermsRequest);
    }
    else {
        $.cookie('MB_GamePermRequestShown', null);
    }
    $(box).dialog('close');
}

function sendGameCredentials(submit_name, submit_score){
    if (submit_score) {
        console.log('Submit_score TRUE!');
    }
    else {
        console.log('Submit_score FALSE!');
    }
    var flash = document.getElementById(gameUniqueName);
    flash.userLoggedIn(submit_name, submit_score);
    submitScore = null;
}

function doReloadAjaxAd(id){
    if ($('#'+id)[0].contentWindow.location != null) {
    	$('#'+id)[0].contentWindow.location.reload(true);
            console.log("AD REFRESHED!");
    }
}

function reloadAjaxAd(){
    if ($('#ajax-ad-game-page-sky')[0].contentWindow.location != null) {
        //console.log("AJAX AD..... after 1500ms...");
        setTimeout(function(){
            $('#ajax-ad-game-page-sky')[0].contentWindow.location.reload(true);
            console.log("AD REFRESHED!");
        }, 1500);
    }
}

$(document).ready(function(){
    initDialogs();
    if (gameControlsAd) {
        if (ajaxAd_sky_IntervalID == null) {
            console.log('ajaxAd_sky_IntervalID undefined');
        }
        else {
            window.clearInterval(ajaxAd_sky_IntervalID);
            console.log('Ad Interval Cleared');
        }
    }
});

//////////////////
// end javascript function library
//
