--[[
	Constants
--]]
Sparkle_Amount = 50; -- Number of particles to use for the mouse sparkle effect.

SOUND_ON_SELECT		= "UISFX_ON_SELECT";
SOUND_ON_BACK		= "UISFX_ON_BACK";
SOUND_ON_CHANGE		= "SOUNDBUTTONCHANGE";
SOUND_ON_NAVIGATE	= "UISFX_ON_FOCUS";
SOUND_ON_FAIL       = "SOUNDBUTTONFAIL"

NETWORK_ERROR_NONE = 0
NETWORK_SERVER_CREATED = 1
NETWORK_SESSION_AVAILABLE = 2
NETWORK_ERROR_CONNECTION_FAILED = 3
NETWORK_ERROR_SERVER_FAILED = 4
NETWORK_ERROR_NO_SESSION_AVAILABLE = 5
NETWORK_ERROR_JOIN_FAILED = 6
NETWORK_JOIN_SUCCESSFUL = 7
NETWORK_SESSION_NOT_LEFT_PROPERLY = 8
NETWORK_SESSION_LEFT_PROPERLY = 9
NETWORK_CONNECTED_TO_2HG = 10
NETWORK_ERROR_CONTENT_MISSING = 11
NETWORK_ERROR_CONNECTING_TO_HOST = 12
NETWORK_ERROR_CABLE_UNPLUGGED = 13
NETWORK_ERROR_SESSION_FULL = 14
NETWORK_ERROR_JOIN_PENDING = 15
NETWORK_ERROR_REQUIRES_CONTROLLER = 16


Blend = {}
Blend.NORMAL = 0
Blend.ADDITIVE = 1
Blend.MODULATE = 2
Blend.SUBTRACTIVE = 3
Blend.SHADOWMAP = 4
Blend.SPECULARMAP = 5
Blend.MODULATEX2 = 6

NetworkMatchType = {}
NetworkMatchType.Player = 0;
NetworkMatchType.Ranked = 1;



CB_NORMAL = 1;
CB_WIDGET_HIGHLIGHT = 5;

function buttonPressSound()
	playSound(SOUND_ON_SELECT);
end

function buttonBackSound()
	playSound(SOUND_ON_BACK);
end

function buttonChangeSound()
	playSound(SOUND_ON_CHANGE);
end

function buttonNavigateSound()
	playSound(SOUND_ON_NAVIGATE);
end

function buttonFailSound()
	playSound(SOUND_ON_FAIL);
end



function Vector(x, y)
    local v = {};
    v.x = x or 0;
    v.y = y or 0;

    v.normalize = function()
        local length = v.length();
        if(length == 0) then
            return;
        end;
        v.x = v.x / length;
        v.y = v.y / length;
    end

    v.scale = function(amount)
        v.x = v.x * amount;
        v.y = v.y * amount;
    end

    v.add = function(v2)
        v.x = v.x + v2;
        v.y = v.y + v2;
    end

    v.length = function()
        return math.sqrt((v.x * v.x) + (v.y * v.y));
    end

    v.createDirection = function(x1, y1, x2, y2)
        v.x = x2 - x1;
        v.y = y2 - y1;
    end

    v.toString = function()
        return "(".. self.x .. "," .. self.y .. ")";
    end;

    return v;
end

loadfile = bzLoadFile;

effectsTable = {};
effectsMetaTable = {__mode = 'k'};
setmetatable(effectsTable, effectsMetaTable);

function addEffect(widgetTableIndex, effectName, effectFunction)

    if(effectsTable[widgetTableIndex] == nil) then
        local t = {};
        effectsTable[widgetTableIndex] = t;
        --print('added effect')
    end

    local co = coroutine.create( function() effectFunction() end)
    effectsTable[widgetTableIndex][effectName] = co;

end;

function hasEffect(widgetTableIndex, effectName)
    if(effectsTable[widgetTableIndex] == nil) then
        return false;
    end;

    if(effectsTable[widgetTableIndex][effectName] == nil) then
        return false;
    end;

   return true;
end

function updateEffects(widgetTableIndex)

   if(effectsTable[widgetTableIndex] == nil) then
       return;
   end

   for k,v in pairs(effectsTable[widgetTableIndex]) do
        --print(k,v)
        local alive, errorMsg  = coroutine.resume(v)

		if  errorMsg then
			dprint ("CORE.LUA CoRoutine Barfed "..errorMsg)
		end

        if (not alive) then
           effectsTable[widgetTableIndex][k] = nil;
        break;
        end;
   end

end

function removeEffect(widget, label)
	effectsTable[widget][label] = nil;
end



--[[
HELPER FUNCTIONS
--]]

--[[
   Util
--]]

function whatis(x)
    print(type(x));
end

--
-- Wait
-- Only call this inside a coroutine.
--

function wait(timeToWait)

    local timeToWait = timeToWait * 1000; -- convert to seconds.

    local startTime = bz_GameTime;
    local currentTime = startTime - bz_GameTime;

    while(currentTime < timeToWait) do
        currentTime =   bz_GameTime - startTime;
        coroutine.yield();
    end
end

--[[
Load in all extras.
--]]



--[[
	Create a big list of blobs, and a render function
--]]



blobTable = {}

function kill()
    blobTable = nil;
    render = nil;
end

-- is the mouse down
mouseDown = 0;

function killBlob(blob)

    local index = -1;
--[[
    table.foreach(blobTable,
        function(k, v)
            if(v == blob) then
                 index = k;
            end
        end);
]]
	for i=1,#blobTable do
		if(blobTable[i] == blob) then
			index = i;
		end
	end

    if(index == -1) then
        return;
    end

    --print('killed blob')
    blobTable[index] = nil;
end

function renderBlobs()
    --table.foreach(blobTable, function(k, v) v:render() end);
	for i=1,#blobTable do
		blobTable[i]:render()
	end
end

function render()
             --table.foreach(blobTable, function(k, v) updateEffects(v) end); anonymous closure will cause an allocation, so don't do it!
			for i=1,#blobTable do
				updateEffects( blobTable[i] )
			end
             --renderBlobs();

             if ( mouseLeftDown() == 1 and mouseDown == 0  ) then
				mouseDown = 1;
             end

             if(mouseLeftDown() == 0 and mouseDown == 1) then
                 mousePop = addBlob();
                 mousePop:setTexture('CURSOR_CLICK');
                 local x,y = mousePos();
                 mousePop:setX(x);
                 mousePop:setY(y);

                 mousePop:setWidth(256);
                 mousePop:setHeight(256);

                 mouseDown = 0;

                 addEffect(mousePop, 'willSelect', willSelect(mousePop));
             end


         end;

function addBlob()
	local b = LuaBlob();
	b:setX(1);
	b:setY(1);
	b:setWidth(16);
	b:setHeight(16);
	b:setColour(255, 255, 255, 255);
	b:setBlendMode( Blend.ADDITIVE );
	b:setTexture('CURSOR_PARTICLE');
	table.insert(blobTable, b);
	return b;
end

function initSparkles()
	sparkleTable = {}
	for i = 1, Sparkle_Amount do
		table.insert(sparkleTable, addBlob());
		sparkleTable[i]:setColour(0, 255, 255, 255);
	end

	Current_Sparkle = 1;

end

function getBlob()
	local b = sparkleTable[Current_Sparkle];
	Current_Sparkle = Current_Sparkle + 1;

	if Current_Sparkle == Sparkle_Amount then
		Current_Sparkle = 1;
	end

	return b;
end

function updateMouseGlow()
	if(MOUSE_GLOW_WIDGET ~= nil) then
		addEffect(MOUSE_GLOW_WIDGET, 'attachToMouse',
		   function()
				 while(true) do
					 local x, y = mousePos();
					 local offSet = 256 * GetYScale()
					 MOUSE_GLOW_WIDGET:setRealPosition(x+offSet, y+offSet);

					 local xdiff = 996 - x;
					 local ydiff = 384 - y;
					 local rot = math.atan2(ydiff, xdiff) * 360/math.pi - 60;
					 MOUSE_GLOW_WIDGET:setRotation(rot);

					 coroutine.yield();
				 end
		   end);
	end
end


function startLuaScripts()

	--if(MOUSE_GLOW_WIDGET ~= nil) then
	--    addEffect(MOUSE_GLOW_WIDGET, 'swirl',
	--	   function()
	--			 while(true) do
	--				 local x, y = mousePos();
	--				 local xdiff = 1270 - x;
	--				 local ydiff = 380 - y;
	--				 local rot = math.atan2(ydiff, xdiff) * 360/math.pi - 60;
	--
	--				 MOUSE_GLOW_WIDGET:setRotation(rot);
	--				 coroutine.yield();
	--			 end
	--	end);
	--end


	print('starting');
	--initSparkles()
    -- This is a hack, m exists merely to hang a coroutine off.
    --m = addBlob();
    --m:setColour(0,0,0,0);
    --addEffect(m, 'mouseSparkle', dropSparkles);

end

function dropSparkles()

	local oldX = 0;
	local oldY = 0;

    while(true) do

        local deadZone = 1;
		local x, y = mousePos();

		if (oldX >= x + deadZone or oldX <= x - deadZone) and
		   (oldY >= y + deadZone or oldY <= y - deadZone) then


			local b = getBlob();

			if isBlobAlphaInvisible(b) then

				b:setColour(255, 255, 255, 255);
				b:setWidth(16);
				b:setHeight(16);

			    b:setX(x);
			    b:setY(y);

			   addEffect(b, 'willParticle', willParticle(b));
			end

        end

		oldX = x;
		oldY = y;
        --wait(0.0001); -- wait a second.
        coroutine.yield();
    end


end

function isBlobAlphaInvisible(blob)

    local a, r, g, b = blob:getColour();
    if a <= 0 then
        return true;
    else
        return false;
    end
end


function willParticle(blob)
    return function()
        local speed = 3;
        local life = 50;
        local v = Vector();
        local originalHeight = blob:getHeight();
        local originalWidth = blob:getWidth();

        v.x = (random(7)-3)/2;
		v.y = (random(7)-3)/2;


        while true do

            blob:setX(blob:getX() + (speed * v.x));
			blob:setY(blob:getY() + (speed * v.y));

			local ap = 100*life/30;

			local x, r, g, b = blob:getColour();
			blob:setColour(ap, r, g, b);

			blob:setWidth(originalWidth * ((ap/2) / 100));
			blob:setHeight(originalHeight * ((ap/2) / 100));

			v.x = v.x + (random(101) - 50) /ap;
			v.y = v.y + (random(101) - 50) / ap;

			life = life-2;

			if life < 2 then
				local x, r, g, b = blob:getColour();
			    blob:setColour(0, r, g, b);
			    return;
			end

			coroutine.yield();
		end
    end
end

function willSelect(blob)

	return function()

	    local originalHeight = blob:getHeight();
        local originalWidth = blob:getWidth();

        local scale = 0.3;
        local alphaDeath = 0.4;
        local alpha = 230;

		blob:setHeight(blob:getHeight() * scale);
		blob:setWidth(blob:getWidth() * scale);

		while true do

		        local pMx, pMy = mousePos();

				blob:setHeight(originalHeight * scale);
				blob:setWidth(originalWidth  * scale);

				blob:setX(pMx - blob:getWidth() / 2);
                blob:setY(pMy - blob:getHeight() / 2);

				scale = scale + 0.07;
				alpha = alpha * alphaDeath;

				local x, r, g, b = blob:getColour();
			    blob:setColour(alpha, r, g, b);

				if scale >= 0.8  then
					killBlob(blob);
					return;
				end

		coroutine.yield();
		end

	end
end




--
-- Menu functionality
--

upsellSettings = {exitUpsell = false}
onlineGameSettings = { rankedMatch = false, justChangedDeck = false}
function isRanked() print(onlineGameSettings.rankedMatch) end;

screenStack = {}

function pushScreen(screen)
	screenStack[#screenStack + 1] = screen;
end

function popScreen()
	local r;
	r = screenStack[#screenStack];
	table.remove(screenStack, #screenStack);
	return r;
end

function goto(from, to)
	pushScreen(from);
	from:setVisible(0);
	to:setVisible(1);
end

function back(from)
	from:setVisible(0);
	local previousScreen = popScreen()
	if previousScreen then
		previousScreen:setVisible(1);
	else
		MAINMENU:setVisible(1)
	end

end

function LeaveUpsellScreen()
      local previousScreen = popScreen()
      if (previousScreen) then
            UPSELL:setVisible(0)
            previousScreen:setVisible(1)
      else
            UPSELL:setVisible(0)
            MAINMENU:setVisible(1)
      end
end

function storeScreen(from)
	pushScreen(from);
end

function onLeaveUpsell()
	UPSELL:setVisible(0);
	refreshActiveScreen();
end

function moveToSinglePlayerScreen()

    -- Move's from the main menu to the single player screen
    setTabIndex(1, 1);
    MAINMENU:setVisible(0);

    SINGLEPLAYER:setVisible(1);


end

function onDoTutorial()

    -- After being prompted for the first time, the user's said they want to do the tutorial.
    OFFINE_GAME_MODES:setVisible(0);
    launchTutorial();
end



function onShowMainMenu()

	SECRETBUTTON:setVisible(1);

	mainmenuUpsellTransform();

	if(MAINMENU_UNLOCKGAME ~= nil) then

		if(isTrialMode() == 1) then
			MAINMENU_UNLOCKGAME:setVisible(1);
		else
			MAINMENU_UNLOCKGAME:setVisible(0);
		end

	end
end

function mainmenuUpsellTransform()
--
-- Grey stuff out that's not available in the trial.
--
	if(isTrialMode() == 1) then
		changeWidgetStyle(MAINMENU_MULTIPLAYER,		CB_NORMAL,				"BZ_GREYED_OUT");
		changeWidgetStyle(MAINMENU_MULTIPLAYER,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
		changeWidgetStyle(MAINMENU_LEADERBOARDS,	CB_NORMAL,				"BZ_GREYED_OUT");
		changeWidgetStyle(MAINMENU_LEADERBOARDS,	CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
		MAINMENU_DOWNLOADCONTENT:setVisible(0);
	else
		changeWidgetStyle(MAINMENU_MULTIPLAYER,		CB_NORMAL,				"BZ_NORMAL");
		changeWidgetStyle(MAINMENU_MULTIPLAYER,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
		changeWidgetStyle(MAINMENU_LEADERBOARDS,	CB_NORMAL,				"BZ_NORMAL");
		changeWidgetStyle(MAINMENU_LEADERBOARDS,	CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
		MAINMENU_DOWNLOADCONTENT:setVisible(1);
	end

end

function mentorUpsellTransform()
--
-- Grey stuff out that's not available in the trial.
--

	if(isTrialMode() == 1) then
		changeWidgetStyle(MAINMENU_BECOMEMENTOR,		CB_NORMAL,				"BZ_GREYED_OUT");
		changeWidgetStyle(MAINMENU_BECOMEMENTOR,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
	else
		changeWidgetStyle(MAINMENU_BECOMEMENTOR,		CB_NORMAL,				"BZ_NORMAL");
		changeWidgetStyle(MAINMENU_BECOMEMENTOR,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
	end

end

function onPressMentorHost()

	if(isTrialMode() == 0) then
		onPressMentorHostMatchButton()
	end

end

function singlePlayerUpsellTransform()
--
-- Grey stuff out that's not available in the trial.
--
	if(isTrialMode() == 1) then
		changeWidgetStyle(SINGLEPLAYER_CHALLENGE,		CB_NORMAL,				"BZ_GREYED_OUT");
		changeWidgetStyle(SINGLEPLAYER_CHALLENGE,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
		changeWidgetStyle(SINGLEPLAYER_CUSTOMDUEL,		CB_NORMAL,				"BZ_GREYED_OUT");
		changeWidgetStyle(SINGLEPLAYER_CUSTOMDUEL,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
		changeWidgetStyle(SINGLEPLAYER_COOP_CUSTOM_DUEL,		CB_NORMAL,				"BZ_GREYED_OUT");
		changeWidgetStyle(SINGLEPLAYER_COOP_CUSTOM_DUEL,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
		changeWidgetStyle(SINGLEPLAYER_LOAD_GAME,		CB_NORMAL,				"BZ_GREYED_OUT");
		changeWidgetStyle(SINGLEPLAYER_LOAD_GAME,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");

	else
		changeWidgetStyle(SINGLEPLAYER_CHALLENGE,		CB_NORMAL,				"BZ_NORMAL");
		changeWidgetStyle(SINGLEPLAYER_CHALLENGE,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
		changeWidgetStyle(SINGLEPLAYER_CUSTOMDUEL,		CB_NORMAL,				"BZ_NORMAL");
		changeWidgetStyle(SINGLEPLAYER_CUSTOMDUEL,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
		changeWidgetStyle(SINGLEPLAYER_COOP_CUSTOM_DUEL,		CB_NORMAL,				"BZ_NORMAL");
		changeWidgetStyle(SINGLEPLAYER_COOP_CUSTOM_DUEL,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
		changeWidgetStyle(SINGLEPLAYER_LOAD_GAME,		CB_NORMAL,				"BZ_NORMAL");
		changeWidgetStyle(SINGLEPLAYER_LOAD_GAME,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
	end
end

function hidePublicPCOnly(widget)

	if isTargetPC() == 1 and isPublic() == 1 then
		widget:setVisible(0);
	else
		widget:setVisible(1);
	end
end

function showPCOnly(widget)

	if widget == nil then
		return
	end

	if isTargetPC() == 1 then
		widget:setVisible(1);
	else
		widget:setVisible(0);
	end

end

function showConsoleOnly(widget)

	if isTargetPC() ~= 1 then
		--widget:setVisible(1);leave it as it is, as you're never going to dynmically switch platform.
	else
		widget:setVisible(0);
	end

end

function showTrialOnly(widget)

	if isTrialMode() == 1 then
		widget:setVisible(1);
	else
		widget:setVisible(0);
	end

end

function hideTrialOnly(widget)

	local isTrial = isTrialMode()
	if (isTrial == 1) then
		widget:setVisible(0);
	else
		widget:setVisible(1);
	end

end

function defaultDiamondSetings()
	cDiamond:setX(false);
	cDiamond:setY(false);
	cDiamond:setB(true);
	cDiamond:setA(true);
	cDiamond:setATag('SELECT');
	cDiamond:setBTag('BACK');
end

function onShowCredits()
	defaultDiamondSetings();
	cDiamond:setA(false);
	--showPCOnly(CREDITS_BACK_BUTTON);
end

function onShowHelpAndOptions()

	if(INGAME_UNLOCK ~= nil) then
		if(isTrialMode() == 1) then
			INGAME_UNLOCK:setVisible(1);
		else
			INGAME_UNLOCK:setVisible(0);
		end
	end

	if (inInnerGame() == 0) then
		HELP_AND_OPTIONS_CUSTOMISATION:setVisible(1)
    else
		HELP_AND_OPTIONS_CUSTOMISATION:setVisible(0)
	end

	--showPCOnly(HELP_AND_OPTIONS_MAINMENU);
	helpAndOptionsTransform();

end

function onShowHowToPlay()
	helpAndOptionsTransform();
end

function onShowInGameMenu()
	if(isTrialMode() == 1) then
		changeWidgetStyle(LOADGAME,		CB_NORMAL,				"BZ_GREYED_OUT");
		changeWidgetStyle(LOADGAME,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
		changeWidgetStyle(SAVEGAME,		CB_NORMAL,				"BZ_GREYED_OUT");
		changeWidgetStyle(SAVEGAME,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
	else
		changeWidgetStyle(LOADGAME,		CB_NORMAL,				"BZ_NORMAL");
		changeWidgetStyle(LOADGAME,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
		changeWidgetStyle(SAVEGAME,		CB_NORMAL,				"BZ_NORMAL");
		changeWidgetStyle(SAVEGAME,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
	end
end

function helpAndOptionsTransform()
	if(isTrialMode() == 1) then
			changeWidgetStyle(HELP_AND_OPTIONS_CUSTOMISATION,		CB_NORMAL,				"BZ_GREYED_OUT");
			changeWidgetStyle(HELP_AND_OPTIONS_CUSTOMISATION,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
			--changeWidgetStyle(HELP_AND_OPTIONS_DECKMANAGER,			CB_NORMAL,				"BZ_GREYED_OUT");
			--changeWidgetStyle(HELP_AND_OPTIONS_DECKMANAGER,			CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
	else
			changeWidgetStyle(HELP_AND_OPTIONS_CUSTOMISATION,		CB_NORMAL,				"BZ_NORMAL");
			changeWidgetStyle(HELP_AND_OPTIONS_CUSTOMISATION,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
			--changeWidgetStyle(HELP_AND_OPTIONS_DECKMANAGER,			CB_NORMAL,				"BZ_NORMAL");
			--changeWidgetStyle(HELP_AND_OPTIONS_DECKMANAGER,			CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");

	end
end

function onPressCustomisation()

	if(isTrialMode() == 1) then
		buttonFailSound()
		goto(HELPANDOPTIONS, UPSELL);
	else
		buttonPressSound()
		HELPANDOPTIONS:setVisible(0);
		CUSTOMISATION:setVisible(1);
	end
end

function onPressStart()

		local guest = isGuest()

		if ( isProfileSignedIn()==1 ) then
			if ( guest ) then
				FlagPlayerSignedOut()
				ShowSignInMessage()
			else
				PRESS_START:setVisible(0);
				STARTING_VIDEO:setVisible(1);
			end
		else
			ShowSignInMessage();
		end

end

function onFinnishStartingBackground()

	if(isProfileSignedIn()==1) then
		if (IsFirstFullLaunch()==0) then
			onHideStartingVid()
			STARTING_VIDEO:setVisible(0);
			MAINMENU:setVisible(1);
		else
			onHideStartingVid()
			STARTING_VIDEO:setVisible(0);
			DIFFICULTY_QUIZ:setVisible(1);
		end
	else
		ShowSignInMessage();
		onHideStartingVid()
		STARTING_VIDEO:setVisible(0);
		PRESS_START:setVisible(1);
	end

end

function onPressSinglePlayer()

 buttonPressSound();
		if(isFirstPlay() == 1) then
			 promptTutorial('onDoTutorial', 'moveToSinglePlayerScreen');

			 -- The dialog boxes do some magic with tab indexes
			 -- This is to override it.

		else
			 moveToSinglePlayerScreen();
		end
end

function onPressLocalCoop()

	buttonPressSound();

	if(isTrialMode() == 1) then
		goto(OFFINE_GAME_MODES, UPSELL)
	else
		OFFINE_GAME_MODES:setVisible(0);
        LOCALCOOP:setVisible(1);
	end
end

function onPressDeckManager(from)

	buttonPressSound();

	if(isTrialMode() == 1) then
		goto(from, UPSELL);
	else
		goto(from, DECKMANAGER_CHOOSEDECK);
	end
end

function onPressDownloadContentPopUp()

	buttonPressSound();

	if(isTrialMode() == 1) then
		goto(MENTORING_LIST, UPSELL);
	else

		if(isTargetPC() == 1) then
			gotoMainMarketPlace();
		else
			--gotoMarketPlace();
			FrontEnd_Download_Content();
		end
		--MAINMENU:setVisible(0);
		--DOWNLOADCONTENT:setVisible(1);
	end
end

function onPressDownloadContent()

	buttonPressSound();

	if(isTrialMode() == 1) then
		goto(MAINMENU, UPSELL);
	else
		gotoMainMarketPlace();
		--MAINMENU:setVisible(0);
		--DOWNLOADCONTENT:setVisible(1);
	end
end

function onPressLeaderBoards()

	 buttonPressSound();

	 ShowLeaderboard();

	--if(isTrialMode() == 1) then

	    -- MAIN MENU EXISTS BEHIND UPSELL.
	--	UPSELL:setVisible(1);
	--	goto(MAINMENU, UPSELL);
	--else
	    --MAINMENU:setVisible(0);
		--print('Leaderboards not implemented yet.');
		--LEADER BOARDS:setVisible(1);
	--end
end

function onPressLaunchChallenge()

	if(isTrialMode() == 1) then
		buttonFailSound()
		goto(SINGLEPLAYER, UPSELL);
	else
		buttonPressSound()
		SINGLEPLAYER:setVisible(0);
		CHALLENGE_SELECTION_SOLO:setVisible(1);
	end
end

function onPressCustomDuel()

	if(isTrialMode() == 1) then
		buttonFailSound()
		goto(SINGLEPLAYER, UPSELL);
	else
		buttonPressSound()
		loadCustomDuelSettings();
		goto(SINGLEPLAYER, CUSTOMDUEL);
	end
end

function onPressCoopCustomDuel()

	if(isTrialMode() == 1) then
		buttonFailSound()
		goto(SINGLEPLAYER, UPSELL);
	else
		if(hasControllerConnected()) then
			customDC:resetPlayers();
			buttonPressSound()
			SINGLEPLAYER:setVisible(0)
			CUSTOMDUEL_COOP:setVisible(1)
		else
			DisplayDialogueErrorMessage('COOP_CONTROLLER_REQUIRED');
		end
	end
end

function onPressLoadGame()
	if(isTrialMode() == 1) then
		UPSELL:setVisible(1);
	else
		SECRET:setVisible(0);
		SAVE_GAME_MANAGER:setVisible(1);
	end
end

function onPressCampaignSolo()

	 buttonPressSound();

	SetSoloCoreCampaign()

    if(isCampaignNew() == 1) then
        SINGLEPLAYER:setVisible(0);
        launchCampaignIntro();
    else
        SINGLEPLAYER:setVisible(0);
        CAMPAIGN_PROGRESS_SOLO:setVisible(1);
    end
end

function onPressCampaignCoop()

	buttonPressSound();
	if(hasControllerConnected()) then
		SetCoopCoreCampaign()
		SINGLEPLAYER:setVisible(0);
		CAMPAIGN_PROGRESS_MULTI:setVisible(1);
	else
		DisplayDialogueErrorMessage('COOP_CONTROLLER_REQUIRED');
	end

end

OPENUP = false; -- force access to some screens.
function openUp()
	print('Opened.');
	OPENUP = true;
end

function doNothing()
    -- sometimes the best thing to do is nothing at all.
end

function stopConnection()
   StopConnection();
end
function retyFindServer()
	onPressJoinOnlineGame();
end

function retryCreateConnection()
	onPressJoinOnlineGame();
end

function retyFindMentorServer()
	onPressSearchMenotrs();
end

function retryCreateMentorConnection()
	onPressSearchMenotrs();
end

function onPressSearchMenotrs()

    local result = CustomMatch(0,1);

    if result == NETWORK_SESSION_AVAILABLE then
		MENTORING_MENU:setVisible(0);
		MENTORING_LIST:setVisible(1);

	elseif result == NETWORK_ERROR_NO_SESSION_AVAILABLE then
		promptNoServer('retyFindMentorServer', 'StopConnection');

	elseif result == NETWORK_ERROR_CABLE_UNPLUGGED then
		ProcessEthernetConnection();
		displayErrorMessage('NETWORK_ERROR_CABLE_UNPLUGGED');

	else
		promptNoConnection('retryCreateMentorConnection', 'doNothing');

	end

end

function onPressJoinOnlineGame()

	recordActivePlayerFor4P2HG();

	if OPENUP == true then
		    SERVER_QUERY:setVisible(0);
			ONLINE_OPTIONS_SERVERLIST:setVisible(1);
			return;
	end



	local result = CustomMatch( 1 ,0  );

    if result == NETWORK_SESSION_AVAILABLE then
	    SERVER_QUERY:setVisible(0);
	    ONLINE_OPTIONS:setVisible(0);
	    RANKED_MATCH:setVisible(0);
        ONLINE_OPTIONS_SERVERLIST:setVisible(1);
	elseif result == NETWORK_ERROR_NO_SESSION_AVAILABLE then
		promptNoServer('retyFindServer', 'StopConnection');
	elseif result == NETWORK_ERROR_CABLE_UNPLUGGED then
		ProcessEthernetConnection();
		displayErrorMessage('NETWORK_ERROR_CABLE_UNPLUGGED');
	else
		promptNoConnection('retryCreateConnection', 'doNothing');
	end

end

function onPressHostOnlineGame()

	buttonPressSound()

	ONLINE_OPTIONS:setVisible(0);
	HOST_GAME_SETTINGS:setVisible(1);
end

function onPressGoto2HGOptions()

	buttonPressSound()
	RANKED_MATCH_HOST:setVisible(0);
	HOST_GAME_SETTINGS:setVisible(0);
	ONLINE_2HG_CHOOSEINPUT:setVisible(1);

end

function onYesDownloadContent()
	onPressDownloadContentPopUp()
	--FrontEnd_Download_Content()
end

function onNoDownload()
	CancelInvitation();
	print('Fill me in with useful code.')
end

function onJoinMentor()

	local result,maxPlayer = JoinMatch(getListBoxRow(MENTORING_LIST_SERVERLISTBOX),1);


    if OPENUP == true then
    	MENTORING_LIST:setVisible(0);
		hideUnusedClientPlayers(maxPlayer);
		MENTEE_LOBBY:setVisible(1);
		return;
    end


    if result == NETWORK_JOIN_SUCCESSFUL then
		MENTORING_LIST:setVisible(0);
		hideUnusedClientPlayers(maxPlayer);
		MENTEE_LOBBY:setVisible(1);

    elseif result == NETWORK_ERROR_JOIN_FAILED then
		MENTORING_LIST:setVisible(0);
		ProcessJoinFail();
		MENTORING_MENU:setVisible(1);
		displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

    elseif result == NETWORK_ERROR_CONTENT_MISSING then
		promptContentMissing('onYesDownloadContent', 'onNoDownload');

	elseif result == NETWORK_ERROR_SESSION_FULL then
		displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

	elseif result == NETWORK_ERROR_CONNECTION_FAILED then
		displayErrorMessage('NETWORK_ERROR_MENTOR_CONNECTION_FAILED');
	elseif result == NETWORK_ERROR_CONNECTING_TO_HOST then
		displayErrorMessage('NETWORK_ERROR_CONNECTING_TO_MENTOR');

    end

end

function onPressJoinSession()
    local result,maxPlayer = JoinMatch(getListBoxRow(ONLINE_OPTION_SERVERLISTBOX),0);


    if OPENUP == true then
    	ONLINE_OPTIONS_SERVERLIST:setVisible(0);
		hideUnusedClientPlayers(maxPlayer);
		CLIENT_LOBBY:setVisible(1);
		return;
    end


    if result == NETWORK_JOIN_SUCCESSFUL then
		ONLINE_OPTIONS_SERVERLIST:setVisible(0);
		hideUnusedClientPlayers(maxPlayer);
		CLIENT_LOBBY:setVisible(1);
	elseif result == NETWORK_CONNECTED_TO_2HG then

		recordActivePlayerFor4P2HG();
		ONLINE_OPTIONS_SERVERLIST:setVisible(0);
		ONLINE_2HG_CHOOSEDECKS:setVisible(1);

    elseif result == NETWORK_ERROR_JOIN_FAILED then
		ONLINE_OPTIONS_SERVERLIST:setVisible(0);
		ProcessJoinFail();
		ONLINE_OPTIONS:setVisible(1);
		displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

    elseif result == NETWORK_ERROR_SESSION_FULL then
		displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

    elseif result == NETWORK_ERROR_CONTENT_MISSING then
		promptContentMissing('onYesDownloadContent', 'onNoDownload');
	elseif result == NETWORK_ERROR_CONNECTION_FAILED then
		displayErrorMessage('NETWORK_ERROR_CONNECTION_FAILED');
	elseif result == NETWORK_ERROR_CONNECTING_TO_HOST then
		displayErrorMessage('NETWORK_ERROR_CONNECTING_TO_HOST');
    end
end

function onPressJoinSession_Steam()
    local result,maxPlayer = JoinMatch(getListBoxRow(ONLINE_OPTION_SERVERLISTBOX), 0);


    if OPENUP == true then
    	ONLINE_OPTIONS_SERVERLIST:setVisible(0);
		hideUnusedClientPlayers(maxPlayer);
		CLIENT_LOBBY:setVisible(1);
		return;
    end


    if result == NETWORK_JOIN_SUCCESSFUL then
		ONLINE_OPTIONS_SERVERLIST:setVisible(0);
		hideUnusedClientPlayers(maxPlayer);
		CLIENT_LOBBY:setVisible(1);
	elseif result == NETWORK_CONNECTED_TO_2HG then
		ONLINE_OPTIONS_SERVERLIST:setVisible(0);
		ONLINE_2HG_CHOOSEINPUT:setVisible(1);
    elseif result == NETWORK_ERROR_JOIN_FAILED then
		ONLINE_OPTIONS_SERVERLIST:setVisible(0);
		ProcessJoinFail();
		ONLINE_OPTIONS:setVisible(1);
		displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

    elseif result == NETWORK_ERROR_CONTENT_MISSING then
		promptContentMissing('onYesDownloadContent', 'onNoDownload');
	elseif result == NETWORK_ERROR_NO_SESSION_AVAILABLE then
		displayErrorMessage('NETWORK_ERROR_CONNECTING_TO_HOST');
	elseif result == NETWORK_ERROR_CONNECTION_FAILED then
		displayErrorMessage('NETWORK_ERROR_CONNECTION_FAILED');
	elseif result == NETWORK_ERROR_CONNECTING_TO_HOST then
		displayErrorMessage('NETWORK_ERROR_CONNECTING_TO_HOST');
    end
end



---
-- This is called from the Host Settings Screen.
-- The user has set the options for the type of server that will be hosted.
---

function onPressMentorHostMatchButton()

	local result = HostMatch(1);

	if(result == NETWORK_SERVER_CREATED) then
			hideUnusedHostPlayers();
			MENTORING_MENU:setVisible(0);
			MENTOR_HOST:setVisible(1);

	elseif result == NETWORK_ERROR_SERVER_FAILED then
		 DisplayDialogueErrorMessage('NETWORK_ERROR_SERVER_FAILED');
	elseif result == NETWORK_ERROR_CABLE_UNPLUGGED then
		displayErrorMessage('NETWORK_ERROR_CABLE_UNPLUGGED');
	 elseif result == NETWORK_ERROR_CONNECTION_FAILED then
		 DisplayDialogueErrorMessage('NETWORK_ERROR_SERVER_FAILED');

		end
end

function onPressHostMatchButton()

	local FOUR_PLAYER_TWO_HEADED_GIANT = 5;

	if getStinkVariable("VAR_HOST_SETTINGS_GAMETYPE") == FOUR_PLAYER_TWO_HEADED_GIANT then
		recordActivePlayerFor4P2HG();
		HOST_GAME_SETTINGS:setVisible(0);
		ONLINE_2HG_CHOOSEDECKS:setVisible(1);
	else
	    onCreateServer();
	end

end

function onPressHostMatchButton_Steam()

	local FOUR_PLAYER_TWO_HEADED_GIANT = 5;

	if getStinkVariable("VAR_HOST_SETTINGS_GAMETYPE") == FOUR_PLAYER_TWO_HEADED_GIANT then
		recordActivePlayerFor4P2HG();
		createSteamGuest();
	else
	    onCreateServer();
	end


end


function onPressHostMatchButton_Online2HG_Steam()

	ONLINE_2HG_CHOOSEINPUT:setVisible(0);
	recordActivePlayerFor4P2HG();
	createSteamGuest_Online2HG();
end


function onCreateServer()
	local result = HostMatch(0);

	if(result == NETWORK_SERVER_CREATED) then
		hideUnusedHostPlayers();
	    HOST_GAME_SETTINGS:setVisible(0);
	    RANKED_MATCH_HOST:setVisible(0);
	    HOST_LOBBY:setVisible(1);

	 elseif result == NETWORK_ERROR_SERVER_FAILED then
		 DisplayDialogueErrorMessage('NETWORK_ERROR_SERVER_FAILED');
	elseif result == NETWORK_ERROR_CABLE_UNPLUGGED then
		displayErrorMessage('NETWORK_ERROR_CABLE_UNPLUGGED');
	 elseif result == NETWORK_ERROR_CONNECTION_FAILED then
		 displayErrorMessage('NETWORK_ERROR_SERVER_FAILED');
	end
end

function onCreateSteamServer2HG()
	local result = HostMatch(0);

	if(result == NETWORK_SERVER_CREATED) then
		hide2HGPlayers();
	    HOST_GAME_SETTINGS:setVisible(0);
	    RANKED_MATCH_HOST:setVisible(0);


	 elseif result == NETWORK_ERROR_SERVER_FAILED then
		 DisplayDialogueErrorMessage('NETWORK_ERROR_SERVER_FAILED');
	elseif result == NETWORK_ERROR_CABLE_UNPLUGGED then
		displayErrorMessage('NETWORK_ERROR_CABLE_UNPLUGGED');
	 elseif result == NETWORK_ERROR_CONNECTION_FAILED then
		 displayErrorMessage('NETWORK_ERROR_SERVER_FAILED');
	end
end

function onClickQuickMatch()

	local guest = isGuest()

	if guest then
		displayErrorMessage('ERROR_GUEST_PROFILE');
	else
		recordActivePlayerFor4P2HG();

		buttonPressSound();

		local result = CustomMatch(  16 , 0 );

		if result == NETWORK_SESSION_AVAILABLE then

				local quickMatchResult,maxPlayer = quickMatch();

				if quickMatchResult == NETWORK_JOIN_SUCCESSFUL then

					ONLINE_OPTIONS:setVisible(0);
					hideUnusedClientPlayers(maxPlayer);
					CLIENT_LOBBY:setVisible(1);

				elseif quickMatchResult == NETWORK_CONNECTED_TO_2HG then

					recordActivePlayerFor4P2HG();
					ONLINE_OPTIONS:setVisible(0);
					ONLINE_2HG_CHOOSEDECKS:setVisible(1);
					return;

				elseif quickMatchResult == NETWORK_ERROR_JOIN_FAILED then

					ProcessJoinFail();
					displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

				elseif result == NETWORK_ERROR_SESSION_FULL then
					displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

				elseif quickMatchResult == NETWORK_ERROR_NO_SESSION_AVAILABLE then
					promptNoServer('onClickQuickMatch', 'StopConnection');

				elseif quickMatchResult == NETWORK_ERROR_CONTENT_MISSING then
					promptContentMissing('onYesDownloadContent', 'onNoDownload');
				end

		elseif result == NETWORK_ERROR_NO_SESSION_AVAILABLE then
			promptNoServer('onClickQuickMatch', 'StopConnection');
		elseif result == NETWORK_ERROR_CABLE_UNPLUGGED then
			ProcessEthernetConnection();
			displayErrorMessage('NETWORK_ERROR_CABLE_UNPLUGGED');
		else
			promptNoConnection('retryCreateConnection', 'doNothing');
		end
	end

end

function onClickQuickMatch_Steam()

	local guest = isGuest()

	if guest then
		displayErrorMessage('ERROR_GUEST_PROFILE');
	else
		recordActivePlayerFor4P2HG();

		buttonPressSound();

		local result = CustomMatch(  16 , 0 );

		if result == NETWORK_SESSION_AVAILABLE then

				local quickMatchResult,maxPlayer = quickMatch();

				if quickMatchResult == NETWORK_JOIN_SUCCESSFUL then

					ONLINE_OPTIONS:setVisible(0);
					hideUnusedClientPlayers(maxPlayer);
					CLIENT_LOBBY:setVisible(1);

				elseif quickMatchResult == NETWORK_CONNECTED_TO_2HG then
						ONLINE_OPTIONS:setVisible(0);
						ONLINE_2HG_CHOOSEINPUT:setVisible(1);

				elseif quickMatchResult == NETWORK_ERROR_REQUIRES_CONTROLLER then
						StopConnection();
                        DisplayDialogueErrorMessage('COOP_CONTROLLER_REQUIRED');

				elseif quickMatchResult == NETWORK_ERROR_JOIN_FAILED then

					ProcessJoinFail();
					displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

				elseif result == NETWORK_ERROR_SESSION_FULL then
					displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

				elseif quickMatchResult == NETWORK_ERROR_NO_SESSION_AVAILABLE then
					promptNoServer('onClickQuickMatch', 'StopConnection');

				elseif quickMatchResult == NETWORK_ERROR_CONTENT_MISSING then
					promptContentMissing('onYesDownloadContent', 'onNoDownload');
				end

		elseif result == NETWORK_ERROR_NO_SESSION_AVAILABLE then
			promptNoServer('onClickQuickMatch', 'StopConnection');
		elseif result == NETWORK_ERROR_CABLE_UNPLUGGED then
			ProcessEthernetConnection();
			displayErrorMessage('NETWORK_ERROR_CABLE_UNPLUGGED');
		else
			promptNoConnection('retryCreateConnection', 'doNothing');
		end
	end

end


function onShowAdvancedOptionsSolo()
	-- CUSTOM DUEL ADVANCED HAS A PROLIFERATION OF SLIDERS
	-- Here they are swept under the rug.

	ADVANCEDOPTIONS_AIDECK_2:setVisible(0);

	ADVANCEDOPTIONS_AIDECK_3:setVisible(0);

	prepareAdvancedOptionsSolo();

end

function onPressSecretDuelSolo()
	SECRET:setVisible(0);
	saveCustomDuelSettings();
	startSecretDuel();
end

function onPressCustomDuelSolo()

	local is360 = isTargetX360()

	if ( is360 ) then

		playSound(SOUND_ON_SELECT);
		CUSTOMDUEL:setVisible(0);


		--addEffect(LOADING, "_", function()
		--
		--						wait(1);
								saveCustomDuelSettings();

								startCustomDuel();

		--						end)
	end
end

function onPressCustomDuelSoloAdvanced()

   playSound(SOUND_ON_SELECT);
   ADVANCEDOPTIONS:setVisible(0);


 --	addEffect(LOADING, "_", function()

--							wait(1);
							saveCustomDuelSettings();
							startCustomDuel();

--							end)
end

function onPressCustomDuelSoloEditor()

  -- playSound(SOUND_ON_SELECT);
   ADVANCEDOPTIONS:setVisible(0);
	saveCustomDuelSettings()
    startCustomDuelEditor();


 --	addEffect(LOADING, "_", function()
--
--							wait(1);
--							saveCustomDuelSettings();
--							startCustomDuelEditor();
--
--							end)
end

function onPressCampaignProgressSolo()


	--playSound(SOUND_ON_SELECT);
	CAMPAIGN_DUEL_SETUP_SOLO:setVisible(0);

	--addEffect(LOADING, "_", function()
	--						wait(1);
							startCampaignSoloDuel();
	--						end)
end

function onPressCampaignProgressMulti()
	--playSound(SOUND_ON_SELECT);
	CAMPAIGN_DUEL_SETUP_MULTI:setVisible(0);

	--addEffect(LOADING, "_", function()
	--						wait(1)
							startCampaignMultiDuel();
	--						end)

end


function onPressAchievements()

	buttonPressSound()
	--if(isTrialMode() == 1) then
	--	UPSELL:setVisible(1);
	--else
		displayAchievements();
	--end
end


----
-- Loading.xml
----

function coPulse(widget)

	return function()
		local pulseSpeed = 150;
		local pulse_A, pulse_R, pulse_G, pulse_B = widget:getNormalColour();
		local alphaValue = 255;

		while(true) do

			widget:setNormalColour(alphaValue, pulse_R, pulse_G, pulse_B);

			alphaValue = alphaValue + (pulseSpeed * bz_dt);

			if(alphaValue <= 0 or alphaValue >= 255) then
				alphaValue = clamp(alphaValue, 1, 254);
				pulseSpeed = pulseSpeed * -1;
			end


			coroutine.yield();
		end
	end

end

function showLoadingScreen()
	doLoadingScreenHint();
	loaidngClearInput();
	startLoadingAnim();
	--LOADINGTEXT_A, LOADINGTEXT_R, LOADINGTEXT_G, LOADINGTEXT_B = LOADINGTEXT:getNormalColour();

	--addEffect(LOADING, 'pulse', coPulse(LOADINGTEXT))
end

----
-- Ranked_Match.xml
----


function onPressHostRankedMatch()

	RANKED_MATCH:setVisible(0);
	RANKED_MATCH_HOST:setVisible(1)

end

function onClickJoinRankedMatch()

	local result = CustomMatch( 1 , 0);

	if OPENUP == true then
        SERVER_QUERY:setVisible(0);
        ONLINE_OPTIONS_SERVERLIST:setVisible(1);
        return;
	end

    if result == NETWORK_SESSION_AVAILABLE then

        SERVER_QUERY:setVisible(0);
        ONLINE_OPTIONS_SERVERLIST:setVisible(1);

	elseif result == NETWORK_ERROR_NO_SESSION_AVAILABLE then
		promptNoServer('retyFindServer', 'StopConnection');
	elseif result == NETWORK_ERROR_CABLE_UNPLUGGED then
		ProcessEthernetConnection();
		displayErrorMessage('NETWORK_ERROR_CABLE_UNPLUGGED');
	else
		promptNoConnection('retryCreateConnection', 'doNothing');
	end

end

----
-- Ranked_Match Client.xml
----
function onClickQuickMatchRanked_Steam()

	local guest = isGuest()

	if guest then
		displayErrorMessage('ERROR_GUEST_PROFILE');
	else

		recordActivePlayerFor4P2HG();

		buttonPressSound();

		local result = CustomMatch( 16 ,0);

		if result == NETWORK_SESSION_AVAILABLE then

				local quickMatchResult,maxPlayer = quickMatch();

				if quickMatchResult == NETWORK_JOIN_SUCCESSFUL then

					RANKED_MATCH:setVisible(0);
					hideUnusedClientPlayers(maxPlayer);
					CLIENT_LOBBY:setVisible(1);

				elseif quickMatchResult == NETWORK_CONNECTED_TO_2HG then
					RANKED_MATCH:setVisible(0);
					ONLINE_2HG_CHOOSEINPUT:setVisible(1);
					return;

				elseif quickMatchResult == NETWORK_ERROR_JOIN_FAILED then

					ProcessJoinFail();
					displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

				elseif result == NETWORK_ERROR_SESSION_FULL then
					displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

				elseif quickMatchResult == NETWORK_ERROR_NO_SESSION_AVAILABLE then
					promptNoServer('onClickQuickMatchRanked', 'StopConnection');

				elseif quickMatchResult == NETWORK_ERROR_CONTENT_MISSING then
					promptContentMissing('onYesDownloadContent', 'onNoDownload');
				end

		elseif result == NETWORK_ERROR_NO_SESSION_AVAILABLE then
			promptNoServer('onClickQuickMatchRanked', 'StopConnection');

		elseif result == NETWORK_ERROR_CABLE_UNPLUGGED then
			ProcessEthernetConnection();
			displayErrorMessage('NETWORK_ERROR_CABLE_UNPLUGGED');

		else
			promptNoConnection('retryCreateConnection', 'doNothing');
		end
	end

end

function onClickQuickMatchRanked()

	local guest = isGuest()

	if guest then
		displayErrorMessage('ERROR_GUEST_PROFILE');
	else

		recordActivePlayerFor4P2HG();

		buttonPressSound();

		local result = CustomMatch( 16 ,0);

		if result == NETWORK_SESSION_AVAILABLE then

				local quickMatchResult,maxPlayer = quickMatch();

				if quickMatchResult == NETWORK_JOIN_SUCCESSFUL then

					RANKED_MATCH:setVisible(0);
					hideUnusedClientPlayers(maxPlayer);
					CLIENT_LOBBY:setVisible(1);

				elseif quickMatchResult == NETWORK_CONNECTED_TO_2HG then

					recordActivePlayerFor4P2HG();
					RANKED_MATCH:setVisible(0);
					ONLINE_2HG_CHOOSEDECKS:setVisible(1);
					return;

				elseif quickMatchResult == NETWORK_ERROR_JOIN_FAILED then

					ProcessJoinFail();
					displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

				elseif result == NETWORK_ERROR_SESSION_FULL then
					displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

				elseif quickMatchResult == NETWORK_ERROR_NO_SESSION_AVAILABLE then
					promptNoServer('onClickQuickMatchRanked', 'StopConnection');

				elseif quickMatchResult == NETWORK_ERROR_CONTENT_MISSING then
					promptContentMissing('onYesDownloadContent', 'onNoDownload');
				end

		elseif result == NETWORK_ERROR_NO_SESSION_AVAILABLE then
			promptNoServer('onClickQuickMatchRanked', 'StopConnection');

		elseif result == NETWORK_ERROR_CABLE_UNPLUGGED then
			ProcessEthernetConnection();
			displayErrorMessage('NETWORK_ERROR_CABLE_UNPLUGGED');

		else
			promptNoConnection('retryCreateConnection', 'doNothing');
		end
	end

end
-- When the player clicks the listbox as a client to a ranked match.
function onPressJoinSessionRanked()

    local result,maxPlayer = JoinMatch(getListBoxRow(ONLINE_OPTION_SERVERLISTBOX),0);

    if result == NETWORK_JOIN_SUCCESSFUL then

		ONLINE_OPTIONS_SERVERLIST:setVisible(0);
		hideUnusedClientPlayers(maxPlayer);
		CLIENT_LOBBY:setVisible(1);
	elseif result == NETWORK_CONNECTED_TO_2HG then

		recordActivePlayerFor4P2HG();
		ONLINE_OPTIONS_SERVERLIST:setVisible(0);
		ONLINE_2HG_CHOOSEDECKS:setVisible(1);
    elseif result == NETWORK_ERROR_JOIN_FAILED then

		ONLINE_OPTIONS_SERVERLIST:setVisible(0);
		ProcessJoinFail();
		RANKED_MATCH:setVisible(1);
		displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

	elseif result == NETWORK_ERROR_SESSION_FULL then
		displayErrorMessage('NETWORK_ERROR_JOIN_FAILED');

    elseif result == NETWORK_ERROR_CONTENT_MISSING then
		promptContentMissing('onYesDownloadContent', 'onNoDownload');

	elseif result == NETWORK_ERROR_NO_SESSION_AVAILABLE then
		displayErrorMessage('NETWORK_ERROR_CONNECTING_TO_HOST');
	elseif result == NETWORK_ERROR_CONNECTION_FAILED then
		displayErrorMessage('NETWORK_ERROR_CONNECTION_FAILED');
	elseif result == NETWORK_ERROR_CONNECTING_TO_HOST then
		displayErrorMessage('NETWORK_ERROR_CONNECTING_TO_HOST');
    end
end

---
-- Ranked_Match_Host.xml
---
function onCreateServerRankedMatch()
	recordActivePlayerFor4P2HG();

	local FOUR_PLAYER_TWO_HEADED_GIANT = 5;

	if getStinkVariable("VAR_HOST_SETTINGS_GAMETYPE") == FOUR_PLAYER_TWO_HEADED_GIANT then

	    -- Move to the card choosing area.
		RANKED_MATCH_HOST:setVisible(0);
	    ONLINE_2HG_CHOOSEDECKS:setVisible(1);

	else
	local result = HostMatch(0);

	if(result == NETWORK_SERVER_CREATED) then
		hideUnusedHostPlayers();
	    RANKED_MATCH_HOST:setVisible(0);
	    HOST_LOBBY:setVisible(1);

	 elseif result == NETWORK_ERROR_SERVER_FAILED then
		 DisplayDialogueErrorMessage('NETWORK_ERROR_SERVER_FAILED');
	elseif result == NETWORK_ERROR_CABLE_UNPLUGGED then
		displayErrorMessage('NETWORK_ERROR_CABLE_UNPLUGGED');
	 elseif result == NETWORK_ERROR_CONNECTION_FAILED then
		 displayErrorMessage('NETWORK_ERROR_SERVER_FAILED');
	end

	end
end




---
-- Unlock the game, upsell, mainmenu, options
---
function onPressUnlockGame()

	buttonPressSound();
	unlockGame();

end

---
-- multiplayer.xml
---

function onClickOnlineGame()
	setupNetworkGame(NetworkMatchType.Player);
end

function onClickRankedOnlineGame()
	setupNetworkGame(NetworkMatchType.Ranked);
end



function masterHostLobbyUpdate()

	if is2HG() == 1 then
		updateHost2HG();
	else
		updateHost();
	end

end



function masterClientLobbyUpdate()

	if is2HG() == 1 then
		updateClient2HG();
	else
		updateClient();
	end

end

function startPressed()

	CheckForCorruptedContent()
	local finished = pressStart_Pressed()

	if(isTargetPC() == 1) then
		Profile_CreateNewProfileIfNeeded_lua()
	end

end

function checkForProfile()

	local profile = Profile_CheckForProfile()
	print(profile)
	if profile then

		PROFILE_CREATE:setVisible(0);
		PROFILE:setVisible(1);

	end

end


function scalePosition(x, y, widget)

	local sizeX, sizeY = getScreenDimentions()
	local modX, modY
	local xScale, yScale

	xScale = sizeX / 1920
	yScale = sizeY / 1080

	modX = x * xScale
	modY = y * yScale

	print(modX)
	print(modY)

	widget:setPosition(modX, modY)

end

function DisplaySecondDeckColours()

	DisplaySecondColourFrame(0);

end

function HideSecondDeckColours()

	HideSecondColourFrame(0);

end

function loadProfile()

	loadSelectedProfile();

end

function deleteProfile()

	deleteSelectedProfile();

end

function clickDeckManager()

	-- To Do: With 2HG deck display must sort out the controller issues.
	if (DIALOGUE:getVisible()) then
		return
	end

	if (PROFILE_CREATE:getVisible()) then
		return
	end

	-- This overrides the flow allowing the user to go to the deck manager
	-- Deck manager will check for the flag and then overrides its own
	-- back function.
	if (UNLOCKED:getVisible()) then
		deckMGR:SetFromUnlockScreen()
		UNLOCKED:setVisible(0)
		DECKMANAGER_CHOOSEDECK:setVisible(1)
	end

	-- For the Coop Campaign
	if ( CAMPAIGN_MULTI_CHOOSEDECKS:getVisible() ) then
		if ( FromPlayer2() ) then
           coopCP:toDeckManager()
           goto(CAMPAIGN_MULTI_CHOOSEDECKS, DECKMANAGER_CHOOSEDECK)
           buttonPressSound()
        end

        return
	end

	-- For the Coop Custom Duel
	if ( CAMPAIGN_MULTI_CHOOSEDECKS:getVisible() ) then
		if ( FromPlayer2() ) then
           coopCP:toDeckManager()
           goto(CAMPAIGN_MULTI_CHOOSEDECKS, DECKMANAGER_CHOOSEDECK)
           buttonPressSound()
        end

        return
	end

	-- For the Host Lobby
	if ( HOST_LOBBY:getVisible() ) then
		if (AllowedInLobby()) then
			FromPlayer2()
			onlineGameSettings.justChangedDeck = true
			goto(HOST_LOBBY, DECKMANAGER_CHOOSEDECK)
		end
		return
	end

	-- For the Client Lobby
	if ( CLIENT_LOBBY:getVisible() ) then
		if (AllowedInLobby()) then
			FromPlayer2()
			onlineGameSettings.justChangedDeck = true
			goto(CLIENT_LOBBY, DECKMANAGER_CHOOSEDECK)
		end
		return
	end

	-- For a normal screen
	if ( PRESS_START:getVisible() == false and
		DECKMANAGER_CHOOSEDECK:getVisible() == false and
		DECKMANAGER:getVisible() == false and
		CHALLENGE_SELECTION_SOLO:getVisible() == false and
		isInGame() == 0 ) then

		local screen = getFirstActiveScreen()
		goto(screen, DECKMANAGER_CHOOSEDECK)

		return
	end

end

function click2ndDeckManager()

	-- To Do: With 2HG deck display must sort out the controller issues.

	-- For the Coop Campaign
	if ( COOP_CAMPAIGN_PROFILE_SELECT:getVisible() ) then
		deckMGR:SetSecondEdit()
        coopCP:toDeckManager()
        goto(COOP_CAMPAIGN_PROFILE_SELECT, DECKMANAGER_CHOOSEDECK)
        buttonPressSound()
        return
	end

	-- For the Coop Custom Duel
	if ( CUSTOMDUEL_COOP:getVisible() ) then
		deckMGR:SetSecondEdit()
		coopCP:toDeckManager()
		goto(CUSTOMDUEL_COOP, DECKMANAGER_CHOOSEDECK)
		buttonPressSound()
        return
	end

	-- For the Host Lobby
	if ( HOST_LOBBY:getVisible() ) then
		FromPlayer2()
		onlineGameSettings.justChangedDeck = true
		goto(HOST_LOBBY, DECKMANAGER_CHOOSEDECK)

		return
	end

	-- For the Host 2HG Lobby
	if ( HOST_LOBBY_2HG:getVisible() ) then
		FromPlayer2()
		deckMGR:SetSecondEdit()
		onlineGameSettings.justChangedDeck = true
		goto(HOST_LOBBY_2HG, DECKMANAGER_CHOOSEDECK)

		return
	end

	-- For the Client Lobby
	if ( CLIENT_LOBBY:getVisible() ) then
		FromPlayer2()
	    onlineGameSettings.justChangedDeck = true
		goto(CLIENT_LOBBY, DECKMANAGER_CHOOSEDECK)

		return
	end

	-- For the Client Lobby 2HG
	if ( CLIENT_LOBBY_2HG:getVisible() ) then
		FromPlayer2()
		deckMGR:SetSecondEdit()
	    onlineGameSettings.justChangedDeck = true
		goto(CLIENT_LOBBY_2HG, DECKMANAGER_CHOOSEDECK)

		return
	end

	-- For the 2HG Controller shizz
	if ( ONLINE_2HG_CHOOSEINPUT:getVisible() ) then
		FromPlayer2()
		deckMGR:SetSecondEdit()
		onlineGameSettings.justChangedDeck = true
		goto(ONLINE_2HG_CHOOSEINPUT, DECKMANAGER_CHOOSEDECK)

		return
	end

end

function ChooseDeck()

	if ( isTargetPC() ~= 1 ) then
		deckMGR:SetSelectedIndex()
	end

	if(deckMGR:selectDeck())then
		ResetMainPlayerIndex()
		deckMGR:filter(true)
		DisplayFirstColourFrame()
		goBack()
		back(DECKMANAGER_CHOOSEDECK)
	end

end

function EditDeck()

	if ( isTargetPC() ~= 1 ) then
		deckMGR:SetSelectedIndex()
	end

	buttonChangeSound();
	deckMGR:selectDeck()
	deckMGR:onClickChooseDeck()
	deckMGR:load()
	deckMGR:ClearSelectedIndex()
    HideFirstColourFrame()
	HideSecondColourFrame()
end

function SelectThisDeck()

	if ( isTargetPC() ~= 1 ) then
		ChooseDeck()
	else
		--if ( deckMGR:isDeckLocked() ~= true) then
			deckMGR:SetSelectedIndex()
			deckMGR:selectDeck()
		--end
	end

end

function setupLoadButton()

	if(isTrialMode() == 0) then
		if (checkForSavedGame()) then
		  changeWidgetStyle(SINGLEPLAYER_LOAD_GAME,		CB_NORMAL,				"BZ_NORMAL");
				changeWidgetStyle(SINGLEPLAYER_LOAD_GAME,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
		else
		  changeWidgetStyle(SINGLEPLAYER_LOAD_GAME,		CB_NORMAL,				"BZ_GREYED_OUT");
				changeWidgetStyle(SINGLEPLAYER_LOAD_GAME,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
		end
    end
end


function deckManagerTrialTransform()
	if(isTrialMode() == 1) then
		changeWidgetStyle(DM_CONSUMEFOILTOKEN,		CB_NORMAL,				"BZ_GREYED_OUT");
		changeWidgetStyle(DM_CONSUMEFOILTOKEN,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
		changeWidgetStyle(DM_CONSUMEDECKUNLOCKTOKEN,		CB_NORMAL,				"BZ_GREYED_OUT");
		changeWidgetStyle(DM_CONSUMEDECKUNLOCKTOKEN,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
	else
		changeWidgetStyle(DM_CONSUMEFOILTOKEN,		CB_NORMAL,				"BZ_NORMAL");
		changeWidgetStyle(DM_CONSUMEFOILTOKEN,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
		changeWidgetStyle(DM_CONSUMEDECKUNLOCKTOKEN,		CB_NORMAL,				"BZ_NORMAL");
		changeWidgetStyle(DM_CONSUMEDECKUNLOCKTOKEN,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
	end
end

function setupInGameLoadButton()
	if(isTrialMode() == 0) then
		if(isSaveLoadValid()) then
			if (checkForSavedGame() ) then
			  changeWidgetStyle(LOADGAME,		CB_NORMAL,				"BZ_NORMAL");
			  changeWidgetStyle(LOADGAME,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
			else
			  changeWidgetStyle(LOADGAME,		CB_NORMAL,				"BZ_GREYED_OUT");
			  changeWidgetStyle(LOADGAME,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
			end
			changeWidgetStyle(SAVEGAME,		CB_NORMAL,				"BZ_NORMAL");
			changeWidgetStyle(SAVEGAME,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
		else
			  changeWidgetStyle(LOADGAME,		CB_NORMAL,				"BZ_GREYED_OUT");
			  changeWidgetStyle(LOADGAME,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
			  changeWidgetStyle(SAVEGAME,		CB_NORMAL,				"BZ_GREYED_OUT");
			  changeWidgetStyle(SAVEGAME,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
		end
	end
end

function setupInGameRestart()

	if(isRestartValid()) then
		changeWidgetStyle(RESTARTGAME,		CB_NORMAL,				"BZ_NORMAL");
		changeWidgetStyle(RESTARTGAME,		CB_WIDGET_HIGHLIGHT,	"BZ_HIGHLIGHT");
	else
		changeWidgetStyle(RESTARTGAME,		CB_NORMAL,				"BZ_GREYED_OUT");
		changeWidgetStyle(RESTARTGAME,		CB_WIDGET_HIGHLIGHT,	"BZ_GREYED_OUT");
	end

end

function ProcessHostQuittingLobby()
		PromptNetworkQuitting('HostLeaveLobby', 'doNothing');
end

function ProcessMentorQuittingLobby()
		PromptNetworkQuitting('MentorLeaveLobby', 'doNothing');
end

function ProcessClientQuittingLobby()
		PromptNetworkQuitting('ClientLeaveLobby', 'doNothing');
end

function ProcessMenteeQuittingLobby()
		PromptNetworkQuitting('MenteeLeaveLobby', 'doNothing');
end

function ProcessKickingMemberQuery()
            PromptKickingMember((getListBoxRow(Lobby_PlayerList)),'KickMember', 'doNothing');
end

function ProcessHostQuittingLobby_2HG()
		PromptNetworkQuitting('HostLeaveLobby_2HG', 'doNothing');
end

function ProcessClientQuittingLobby_2HG()
		PromptNetworkQuitting('ClientLeaveLobby_2HG', 'doNothing');
end
