/*


This script exist to manage things in an easier way than with the scripts in the compressors.

Caller : 00_00_top.php

CREATION  : 221221



 */
function MainVpJs(){

	let self = this;

	// debug
	//-----------------------------------
	this.debug = false;


	// userData will be stored in a cookie;
	// They contain : 
	// 		- the number of viewed pages
	// 		- the number of games played
	// 		
	// 		in a day and from the begining (Ever);
	// 		
	// 		The uDEver also stores the onboarding games results.
	// 		uDEver : 
	// 		{
	// 			'plays':N, 
	// 			'pages':N, 
	// 			'popupHasBeenClosed':N,
	// 			'OTfinished': 1 or 0,
	// 			'aOG':[
		// 				{gid:, score:}, 
		// 				{....}
	// 				]
	// 		}
	// 		
	// 	The cookie uDEver is not supposed to be destroyed.
	// 	The cookie uDDay is renewed every day
	// 	
	// 	NOTE : we have aOG for the score storing but we don't use it.
	// 	
	//-----------------------------------
	let uDEver = {};

	// Stores things. Destroyed every day.
	// Structure : 
	// 	{
	// 		"plays": 1,
	// 		"pages": 623,
	// 		"battles": [{id:, game_id:}, ...]
	// 	}
	// 		
	//-----------------------------------
	let uDDay = {};



	

	// The limit before we do not display anything anymore.
	// Should be 2 in prod.
	//-----------------------------------
	let popupHasBeenClosedLimit = 2; 

	// Nb games to be displayed
	//-----------------------------------
	let nbGamesToBeDisplayed = 3;

	// popupIndex
	//-----------------------------------
	let popupIndex;

	// Will be set to 1 on the display of the last OTunnel popup.
	//-----------------------------------
	uDEver.OTfinished = 0;

	// plays_total_count limit : the thershold before considering the user is not a new one.
	//-----------------------------------
	let plays_total_count_limit = 5;

	// The user status :
	// 		• nb visit, nb pages
	// 		
	//-----------------------------------
	let uStatus;


	// The popup status 
	//-----------------------------------
	this.isPopupDisplayed = false;


	//----------------------------------------------------------
	// >> INIT
	//----------------------------------------------------------

	/**
	 * [init description]
	 * @return {[type]} [description]
	 */
	this.init = function(){

		// Dark mode
		//-----------------------------------
		this.initDarkMode();

		
		// Resources init for the onboardingTunnel
		//-----------------------------------
		this.initOnboardingTunnel();

		// Notifications
		//-----------------------------------
		if (IS_MEMBER && IS_MOBILE){
			this.mngNotifications();
		}
	}



	/*#########################################
	# >>	user name.
	#########################################*/

	/**
	 * [functon description]
	 * @param  OBJ o An object with all the user data.
	 *               {id: ,login:, avatarCode: , is_premium: ,reputation; ,}
	 * @param  STRING options An object with the options.
	 *               "xs | md | xl,  in_list text_only in_hof, avatar_only, no_link"
	 *               
	 * @return {[type]}   [description]
	 */
	this.displayUserName = function(o, options, path){
		// Path
		//-----------------------------------
		if(typeof path === "undefined") path = ""

		// Options :
		//-----------------------------------
		if(typeof options === "undefined") options = ""

		// Options and classAdded
		//-----------------------------------
		let classAdded = "xs";
		let a = options.split(" ");
		if (a.indexOf('xl') !== -1) classAdded = "xl";
		if (a.indexOf('md') !== -1) classAdded = "md";

		if (a.indexOf('battle_style') !== -1) classAdded += " battle_style";
		if (a.indexOf('small') !== -1) classAdded += " small";

		// Options
		//-----------------------------------
		let avatar_only = a.indexOf('avatar_only') !== -1
		if( avatar_only ) classAdded += ' avatar_only'
		let text_only = a.indexOf('text_only') !== -1
		if( text_only ) classAdded += ' text_only'
		let no_link = a.indexOf('no_link') !== -1
		if( no_link ) classAdded += ' no_link'

		// The start
		//-----------------------------------
		let out = `<span class='user_name ${classAdded}'>`;
		// Avatar
		//-----------------------------------
		if ( o.code == null ) o.code = '' // Little patch because during dev o.code can be null from the DB.
		if (!text_only){
			out += `<div class='avatar ${classAdded}' id='av${o.id}' data-code='${o.code}'><span class='code'>${o.code}</span></div>`;
		}

		// login
		//-----------------------------------
		out += `<span class='name' style='margin-left:5px;'>`
		let profileUrl = path + `-_pageid226_upid=${o.id}.html`;
		if (!no_link){
			out += `<a href='${profileUrl}' class='login_link'>${o.login}</a>`; 
		}else{
			out += `${o.login}`; 
		}
		// Premium (not for the moment.).
		//-----------------------------------
		// let ico = o.premiumOrigin == 'free_period' ? "sun-o" : "certificate";
		// out += `<a href='_pageid82.html' class=''><i class='fa fa-${ico} premium_ico_link'></i></a>`

		// End
		//-----------------------------------
		out += `</span>`;
		out += `</span>`; 

		// Return
		//-----------------------------------
		return out;
	}



	/*#########################################
	# >>	gameThumb
	#########################################*/
	/**
	 * [game_thumb description]
	 * @param  [type] o : {id:, special_id:, parent_id:, name:, score_max}
	 * @param  string $type            [description]
	 * @param  string $class           game_thumb_160, game_thumb_200
	 * @return [type]                  [description]
	 */
	this.buildGameThumb = function(game_special_id, type, _class){
		// Options :
		//-----------------------------------
		if(typeof type === "undefined"){ type = "img";}
		if(typeof _class === "undefined"){ _class = "";}

		// type :
		//-----------------------------------
		var a = type.split(" ");
		let is_img = a.indexOf('img') !== -1;
		let is_text = a.indexOf('text') !== -1;
		let is_stars_only = a.indexOf('stars_only') !== -1;
		let is_no_link = a.indexOf('no_link') !== -1;
		let is_w_nb_played = a.indexOf('nb_played') !== -1;

		// Vars setting
		//-----------------------------------
		const game_thumb = GAMES_COLLECTION[game_special_id].thumb
		const game_id = GAMES_COLLECTION[game_special_id].id
		const game_score_max = GAMES_COLLECTION[game_special_id].score_max
		const game_views = GAMES_COLLECTION[game_special_id].views
		const game_name = GAMES_COLLECTION[game_special_id].name
		const game_is_new = GAMES_COLLECTION[game_special_id].is_new
		const game_link = GAMES_COLLECTION[game_special_id].link
		const game_premium_only = typeof GAMES_COLLECTION[game_special_id].premium_only === 'undefined' ? 0 : GAMES_COLLECTION[game_special_id].premium_only

		// game_premium_only
		//-----------------------------------
		let premium_only_class = "";
		if (game_premium_only == 1) premium_only_class = "premium_only";

		// We build
		let str = "";
		if (is_no_link == false){
			str += `<a href='${game_link}' class='game_thumb ${_class} ${type} ${premium_only_class}'>`;

		}else{
			str += `<span class='game_thumb ${_class} ${type}'>`;
		}
		if (is_img){

			game_thumb_class = game_special_id;
			str += `<div class='game_thumb_img ${game_thumb_class}'></div>`;

			// is_new
			//-----------------------------------
			if (game_is_new == 1){
				str += `<div class='is_new'></div>`;
			}

			if (game_is_new == 2){
				str += `<div class='is_new_version'></div>`;
			}

			if (game_premium_only){
			//	$str .= "<div class='premium_ico'><i class='fa fa-lock'></i></div>";
			}

		}

		// if (is_w_nb_played){
		// 	str += `<div class='nb_played'>${game_views} ${LANG_nb_plays_abr}</div>`;
		// }

		if (is_text){
			str += `<span class='game_name'>${game_name}</span>`;
		}
		str +=`<div class='game_id' style='display:none;'>${game_id}</div>
				<div class='game_special_id' style='display:none;'>${game_special_id}</div>
				<div class='game_score_max' style='display:none;'>${game_score_max}</div>`;

		if (is_no_link == false){
			str +=`</a>`;
		}else{
			str +=`</span>`;
		}	
		
		return str;
	}

	/**
	 * [buildGameThumbFlash description]
	 * @param  {[type]} game_special_id [description]
	 * @return {[type]}                 [description]
	 */
	this.buildGameThumbFlash = function(game_special_id){

		const game_id = GAMES_COLLECTION[game_special_id].id
		const game_name = GAMES_COLLECTION[game_special_id].name
		let out = `
			<div class='gameThumbFlash' style='background-image:url(images/games_big_thumbs/${game_special_id}_flash.jpg)'>

				<div class='gameThumbFlashName'>${game_name}</div>
			</div>`;

		return out;
	}


	/*#########################################
	# >>	gameData resources
	#########################################*/

	/**
	 * [addGameDataFromId description]
	 * @param {[type]} game_id [description]
	 */
	this.gameDataFromId = function(game_id){
		for(key in GAMES_COLLECTION){
			if (GAMES_COLLECTION[key].id == game_id) return GAMES_COLLECTION[key]
		}
		return false;
	}
	/**
	 * [gameDataFromSpecialId description]
	 * @param  {[type]} game_special_id [description]
	 * @return {[type]}                 [description]
	 */
	this.gameDataFromSpecialId = function(game_special_id){
		if (typeof GAMES_COLLECTION[game_special_id] !== 'undefined'){
			return GAMES_COLLECTION[game_special_id]
		}else{
			return false;
		}
	}


	/*#########################################
	# >>	toggleDarkMode
	#########################################*/

	/**
	 * [initDarkMode description]
	 * @return {[type]} [description]
	 */
	this.initDarkMode = function(){
		// The button darkMode
		//-----------------------------------
		$("#btnToggleDarkMode").click(function(event) {
			self.toggleDarkMode()
		});
	}

	/**
	 * Check the cookie "darkMode"
	 * @return {[type]} [description]
	 */
	this.toggleDarkMode = function(){
		
		let cookieDarkMode = getCookie('darkMode');
		if (cookieDarkMode == ""){
			setCookie('darkMode', 1, 360)
			G_DARKMODE = 1 // useless
			loadDarkModeCssInBottom()
			loadDarkModeCssFile()
		}else{
			setCookie('darkMode', 0, -1)
			G_DARKMODE = 0 // useless
			$('link[rel=stylesheet][href~="css/dark_mode_001.css"]').remove();
			reload_page();
		}

	}






	/*#########################################
	# >>	ONBOARDING TUNNEL
	#########################################*/


	/**
	 * Everything for the OT
	 * @return {[type]} [description]
	 */
	this.initOnboardingTunnel = function(){
		// We set the stat vars from the cookies
		//-----------------------------------
		let tmpEver = getCookie('uDEver');
		let tmpDay = getCookie('uDDay');

		// From the cookie to the var 
		//-----------------------------------
		if (tmpEver != ""){
			tmpEver = JSON.parse(b64Decrypt(tmpEver));
			uDEver.plays = tmpEver.plays;
			uDEver.pages = tmpEver.pages;
			uDEver.OTfinished = tmpEver.OTfinished;
			uDEver.popupHasBeenClosed = tmpEver.popupHasBeenClosed;

			uDEver.aOG = tmpEver.aOG;
			uDEver.soundPrefs = tmpEver.soundPrefs;
		

		// If the cookie doesn't exist, we set some default values
		//-----------------------------------
		}else{
			this.setDefaultValues();
		}

		// From the cookie to the var 
		//-----------------------------------
		if (tmpDay != ""){
			tmpDay = JSON.parse(b64Decrypt(tmpDay));
			uDDay.plays = tmpDay.plays;
			uDDay.pages = tmpDay.pages;
			uDDay.battles = tmpDay.battles;
		}

		if (this.debug) console.log(JSON.stringify(uDEver));


		// A new page is viewed
		//-----------------------------------
		this.storePages();

		// The action in case of game page (will do nothing if not a game page).
		//-----------------------------------
		this.buttonStartGameAction();

		// Display onboard tunnel or not (if ONBOARDING_TUNNEL_ENABLED).
		//-----------------------------------
		if (typeof ONBOARDING_TUNNEL_ENABLED !== 'undefined' && ONBOARDING_TUNNEL_ENABLED == true){

			// Display onboard tunnel popup
			//-----------------------------------
			if (this.isUserInOTMode()){
				// Are we on a OTunnel special game page => no popup
				//-----------------------------------
				if (this.isOTunnelSpecialGamePage() == false){

					this.displayOTPopup();

				}else{
					if (this.debug) console.log("no popupOTunnel : OTgame page");
				}

			}

			// At each OT special game page, we reset the credit_count cookie.
			// This way we deal with #alert_credit_count_reached_game_blocker in these pages 
			// AND we allow the user to play 3 times after his first flash game plays.
			//-----------------------------------
			if (this.debug){
				console.log("this.isUserInOTMode() : "+this.isUserInOTMode());
				console.log("this.isOTunnelSpecialGamePage() : "+this.isOTunnelSpecialGamePage());
			}

			if(this.isOTunnelSpecialGamePage() && this.isUserInOTMode()){
				setCookie('credit_count', 0, -1);
				setCookie('credit_count_reached', 0, -1);
				setCookie('plays_total_count', 0, -1);
			}
		}
	}

	/**
	 * [setDefaultValues description]
	 */
	this.setDefaultValues = function(){
		// The default
		//-----------------------------------
		uDEver.plays = 0;
		uDDay.plays = 0;

		uDEver.pages = 0;
		uDDay.pages = 0;

		uDDay.battles = [];

		uDEver.popupHasBeenClosed = 0;
		uDEver.soundPrefs = { soundOn:true, musicOn:true };

		uDEver.aOG = [];
		for (var i = 0; i < OT_GAMES.length; i++) {
			uDEver.aOG.push({gid:OT_GAMES[i].id, score:0});
		}

	}


	/*#########################################
	# >>	Plays and Pages
	#########################################*/

	/**
	 * Store the user plays in a cookie (some of them are emptied everyday)
	 *
	 *
	 * CALLER : each time a play is started.
	 *  
	 * @return {[type]} [description]
	 */
	this.storePlays = function(){
		
		uDEver.plays ++;
		uDDay.plays ++;
		
		this.saveOTCookies();
	}

	/**
	 * Increment the page viewed vars
	 * @return {[type]} [description]
	 */
	this.storePages = function(){
		
		uDEver.pages ++;
		uDDay.pages ++;
		
		this.saveOTCookies();
	}


	/**
	 * Stores battle started
	 */
	this.storeBattle = function(battle_id, game_id){

		// Secutity : 
		//-----------------------------------
		if (typeof uDDay.battles === 'undefined') uDDay.battles = []
		uDDay.battles.push({id:battle_id, game_id:game_id});
		
		this.saveOTCookies();
	}


	/**
	 * Saves the sound preferences.
	 *
	 * @param      {<type>}  o       part or entire set of prefs
	 */
	this.saveSoundPrefs = function(o){

		// We update the pref in input (which are not the entire set of prefs)
		//-----------------------------------
		let a = Object.keys(o)
		a.map((item) => {
			uDEver.soundPrefs[item] = o[item]
		})

		this.saveOTCookies();
	}

	/**
	 * Gets the battles.
	 *
	 * @return     {array}  The battles array = [{id:, game_id:}]
	 */
	this.getBattlesOfTheDay = function(){
		return uDDay.battles
	}

	/**
	 * Gets the battles from uDEver. (sound and music pref)
	 *
	 * @return     {array}  The battles array = [{id:, game_id:}]
	 */
	this.getSoundPrefs = function(){
		// The first time soundPrefs is called, it's not set.
		//  	Lets initiate that :
		//-----------------------------------
		if (typeof uDEver.soundPrefs === 'undefined'){
			uDEver.soundPrefs = { soundOn:true, musicOn:true }
			this.saveSoundPrefs(uDEver.soundPrefs)
		}

		// Then return
		//-----------------------------------
		return uDEver.soundPrefs
	}


	/**
	 * To know if we have to play a sound or not (when we 
	 * don't want to use the whole VpSoundCtrl object.
	 */
	this.getSoundOn = function(){
		let o = this.getSoundPrefs()
		return o.soundOn
	}


	/**
	 * [saveOTCookies description]
	 * @return {[type]} [description]
	 */
	this.saveOTCookies = function(){
		
		let uDEverStr = b64Encrypt(JSON.stringify(uDEver));
		let uDDayStr = b64Encrypt(JSON.stringify(uDDay));

		setCookie('uDEver', uDEverStr, 365);
		setCookie('uDDay', uDDayStr, 1);
		
	}

	/**
	 * To add easily plays features, I added an action on the buttonStart.
	 * Caller : this.init();
	 * @return {[type]} [description]
	 */
	this.buttonStartGameAction = function(){
		if ($("#buttonStart", "#game_outer").length > 0){
			$("#buttonStart", "#game_outer").click(function(event) {
				self.storePlays();
			});
		}
	}


	/**
	 * Check if the user is in OT mode : do we have to display the popup, check cookies ....
	 *
	 * The conditions : 
	 * 		• The user is a new one
	 * 		• IS_MOBILE = false (too complicated to deal with small screens)
	 * 	 	• The user has not finished the OTunnel
	 * 	 	• The user hasn't already close the popup twice
	 * 	 	• The current page is not one of the flash games (the OTunnel special games);
	 *
	 * The consequences :
	 * 		• If the OTunnel popup is displayed, no other popup has to be on air.
	 * 			- ex : plugins/vp_simple_push/01_display_simple_push.php
	 * 				- We do not allow the display of the simple_push if the OTunnel popupis here.
	 * 	 	
	 * @return {[type]} [description]
	 */
	this.isUserInOTMode = function(){

		if (this.debug) console.log("OTunnel analyse");

		// Too complicated to manage for mobile :
		//-----------------------------------
		if (IS_MOBILE) return false;

		// Is the user a real new one ?
		//-----------------------------------
		if (IS_MEMBER == false && getCookie('plays_total_count') < plays_total_count_limit){

			// This is a real new user.
			// Has the popup been closed 2 times ? Is yes, we don't display the popup, the user doesn't want it.
			//-----------------------------------
			if (uDEver.popupHasBeenClosed < popupHasBeenClosedLimit){

				// The user has finished the OT ? Is yes, we don't display the popup,
				//-----------------------------------
				if (uDEver.OTfinished == 0){

					
						// return
						//-----------------------------------
						return true;
						
					
				}else{
					if (this.debug) console.log("User not in OTunnel : OTfinished == ");
				}
			}else{
				if (this.debug) console.log("User not in OTunnel : popupHasBeenClosed : " + popupHasBeenClosedLimit);
			}

		}else{
			if (this.debug) console.log("User not in OTunnel : IS_MEMBER OR 'plays_total_count' limit reached");
		}

		// Default return
		//-----------------------------------
		return false;
	}


	/**
	 * Return true if the current page is containing one of the OTunnel special games.
	 * @return {Boolean} [description]
	 */
	this.isOTunnelSpecialGamePage = function(){
		let res = false;
		let gid

		if (typeof G_GAME_ID !== 'undefined'){
			for (var i = 0; i < OT_GAMES.length; i++) {
				gid = OT_GAMES[i].id;
				if (gid == parseInt(G_GAME_ID)){
					res = true;
					break;
				}
			}
		}
		return res;
	}

	/**
	 * We have a lot of popups. We want only one per page.
	 * If the OT popup is displayed : no other can be displayed
	 * If we are in a OT game page : no popup guest can be displayed (see plugins/vp_simple_push/01_display_simple_push.php);
	 * @return {[type]} [description]
	 */
	this.isOtherPopupAllowed = function(){
		if (this.isOTunnelSpecialGamePage()) return false;
		if (this.isPopupDisplayed) return false;
		return true;
	}

	/**
	 * [displayOTPopup description]
	 * @return {[type]} [description]
	 */
	this.displayOTPopup = function(){

		// Var
		//-----------------------------------
		let str;

		// We will display different games according to the saved scores.
		// If there is no saved score, start_index = 0, if there is one, start_index = 3;
		//-----------------------------------
		let start_index = 0;
		let nbSavedScores = 0;
		for (var i = 0; i < OT_GAMES.length; i++) {
			if (uDEver.aOG[i].score > 0) nbSavedScores ++;
		}


		// DEV : to test the different popups : 
		// nbSavedScores = 0;
		// nbSavedScores = 1;
		// nbSavedScores = 2;
		// nbSavedScores = 3;


		popupIndex = nbSavedScores + 1;

		// We create the bloc that will contain the popup code
		//-----------------------------------
		$("body").append("<div id='oTPopupBloc'></div>");

		

		// The start code : 
		//-----------------------------------
		str = `
			<div class='popup_overlay popupOTunnel_overlay flex '>
				<div class='popup popupOTunnel dark_bloc'>
					<i class='fa fa-times-circle btn_close pointer'></i>
					<div class='popupOTunnel_avatar'></div>`;

		// If there are games thumbs to be displayed, we display them
		//-----------------------------------
		if (nbSavedScores < 3){
			str += this.setContentPopupWithGames(popupIndex);
		}


		// If there are NO games thumbs to be displayed, we display the last popup
		//-----------------------------------
		if (nbSavedScores == 3){
			str += this.setContentPopupWithoutGames();
		}

		// End code
		//-----------------------------------
		str += `</div>
			</div>`;

		// The code pushing
		//-----------------------------------
		$("#oTPopupBloc").html(str);

		$(".popup", "#oTPopupBloc").draggable();

		// The btn_close : if closed 2 times, we have to stop displaying the OTpopup.
		//-----------------------------------
		$(".popupOTunnel > .btn_close").click(function(event) {
			$(".popupOTunnel_overlay").remove();
			self.setOTPopupHasBeenClosed();
		});

		// Broadcast
		//-----------------------------------
		this.isPopupDisplayed = true;
	}

	/**
	 * [diplayPopupWithGames description]
	 * @param  {[type]} start_index [description]
	 * @return {[type]}             [description]
	 */
	this.setContentPopupWithGames = function (popupIndex){

		//console.log(start_index);

		// Should be :
		// 0 if popupIndex == 1
		// 3 if popupIndex == 2
		// 6 if popupIndex == 3
		let start_index;
		if (popupIndex == 1) start_index = 0;
		if (popupIndex == 2) start_index = 3;
		if (popupIndex == 3) start_index = 6;

		// Onboard_tunnel JS
		//-----------------------------------
		let lang_index = popupIndex; // == 0 ? "1" : "2";

		//console.log(lang_index);

		let pTitle = $("#LANG_OTunnel_popup_title_"+lang_index).html();
		let pMainText= $("#LANG_OTunnel_popup_main_text_"+lang_index).html();
		let strAdded;
		var str = `
			<div class='content flex flex_col'>
				<h3>${pTitle}</h3>
				<p class='text-center'>${pMainText}</p>
			</div>

			<div class='gameThumbsBloc flex flex_sb margin-top-20'>`;

			let l = start_index + nbGamesToBeDisplayed;
			if (l > OT_GAMES.length) l = OT_GAMES.length;

			console.log(l);

			for (var i = start_index; i < l; i++) {
				let gsid = OT_GAMES[i].special_id;
				let gid = OT_GAMES[i].id;
				let gurl = OT_GAMES[i].url;

				// Add of a fa-check if the game has been played
				//-----------------------------------
				strAdded = ``;
				// COMMENTED : NO NEED : we don't display a thumb once the game has been played.
				// if (uDEver.aOG[this.getOTGameIndex(gid)].score > 0){
				// 	strAdded += `
				// 	<div class='game_done'>
				// 		<i class='fa fa-check'></i>
				// 	</div>`;
				// }

				str += `
				<div id='game_big_thumb_${gsid}' class="game_big_thumb_bloc">
					${strAdded}
					<a href="${gurl}">
						<div class="game_big_thumb" style='background-image:url(images/games_big_thumbs/${gsid}.jpg'></div>
						<img src="images/game_titles/game_title_${gsid}.png" class='game_title'>
					</a>
				</div>`;
			}

		str += `
			</div>
		`;

		// Returns
		//-----------------------------------
		return str;
	}


	/**
	 * Return a str with the content of a simple popup, without game thumbs.
	 */
	this.setContentPopupWithoutGames = function(){
		let pTitle = $("#LANG_OTunnel_popup_title_4").html();
		let pMainText= $("#LANG_OTunnel_popup_main_text_4").html();
		let pBtnSignUp= $("#LANG_OTunnel_popup_btn_signup").html();
		var str = `
				<div class='content flex flex_col'>
					<h3>${pTitle}</h3>
					<p class='text-center'>${pMainText}</p>

					<button id="register_button_in_otpopup" class="btn btn-warning btn_premium_orange_big" style="word-wrap: none;" onclick="go2page('-register_pageid57.html')">
											<nobr>${pBtnSignUp}</nobr></button>
				</div>`;


		// The user has finished the Onboarding tunnel, we flag it :
		//-----------------------------------
		uDEver.OTfinished = 1;

		this.saveOTCookies();

		// Returns
		//-----------------------------------
		return str;

	}




	/**
	 * Simply increment (or create) a var in the cookie uDEver and save the cookie.
	 */
	this.setOTPopupHasBeenClosed = function(){
		uDEver.popupHasBeenClosed ++;

		this.saveOTCookies();
	}



	/*#########################################
	# >>	OT GAMES SCORE MANAGEMENT (USELESS)


		DEPRECATED


	#########################################*/


	/**
	 * Save the score in cookie if needed.
	 * CALLERS : the _jeux/_common/[LOc|Reg|QUIZ]Wrapper.js
	 *
	 * NOTE : We use the saved scores only to know where the user is in the OT process (which popup have we to display).
	 * 
	 * @param  {[type]} game_id     [description]
	 * @param  {[type]} playerScore [description]
	 * @return {[type]}             [description]
	 */
	this.manageOTGameScore = function(game_id, playerScore){

		if (this.debug) console.log(playerScore+ " <=======");

		//return; // NOT USED FOR THE MOMENT
		

		// Is the game an OT game ?
		//-----------------------------------
		if (this.isOTGame(game_id)){

			// Is the score better than the saved one ?
			// Then we store and save.
			//-----------------------------------
			let game_index = this.getOTGameIndex(game_id);
			if (uDEver.aOG[game_index].score < playerScore){

				uDEver.aOG[game_index].score = playerScore;
				this.saveOTCookies();
			}
		}
	}

	/**
	 * [isOTGame description]
	 * @param  {[type]}  game_id [description]
	 * @return {Boolean}         [description]
	 */
	this.isOTGame = function(game_id){
		let res = false;
		for (var i = 0; i < OT_GAMES.length; i++) {
			if (game_id == OT_GAMES[i].id) res = true;
		}
		return res;
	}

	/**
	 * Retruns the index of the desired game id in the OT_GAMES array;
	 * @return {[type]} [description]
	 */
	this.getOTGameIndex = function(game_id){
		for (var i = 0; i < uDEver.aOG.length; i++) {
			if (game_id == uDEver.aOG[i].gid) return i;
		}
		return -1;
	}



	/*#########################################
	# >>	Notifications for mobiles
	#########################################*/
	
	/**
	 * Check if there are notifications.
	 * 		If Yes : build a bell button to access a popup with the notif.
	 *
	 * CALLED only for IS_MEMBERS
	 * 
	 * @return {[type]} [description]
	 */
	this.mngNotifications = function(){

		// The notifications
		//-----------------------------------
		if ($("#login_form_bloc > #notification_bloc > li").length > 0){

			this.displayMobileNotifs();
		}

		// The simple notifications
		//-----------------------------------
		if ($("#simple_notification_bloc_inner > li").length > 0){
			this.displayMobileSimpleNotifs();
		}

	}

	
	/**
	 * [displayMobileNotifs description]
	 * @return {[type]} [description]
	 */
	this.displayMobileNotifs = function(){
		// The notifications number : we add all the badge's text (bad code).
		//-----------------------------------
		let nbNotif = 0;
		$(".badge", "#login_form_bloc > #notification_bloc > li").each(function(index, el) {
			nbNotif += parseInt($(this).text());
		});
		// We detach and store the content of the notification bloc.
		//-----------------------------------
		let liNotif = $("#login_form_bloc > #notification_bloc > *").detach();

		let str = `
		<div id='btnDisplayPopupNotif'>
			<i class='fa fa-bell'></i><span class="badge badge_red">${nbNotif}</span>
		</div>

		<div id='popupNotifications' class='vpPopup' style='display:none;'>
			<i class='fa fa-times-circle ico_close_popup'></i>
			<div id='popupNotificationsList' class='popupContent'></div>
		</div>`;

		$("#login_form_bloc > #notification_bloc").append(str);
		$("#login_form_bloc > #notification_bloc").show();

		liNotif.appendTo("#popupNotificationsList");

		$("#btnDisplayPopupNotif").click(function(event) {
			$("#popupNotifications").show();
		});
		$("#popupNotifications > .ico_close_popup").click(function(event) {
			$("#popupNotifications").hide();
		});

	}


	/**
	 * The same thannotifications, but for the simple notifs.
	 * @return {[type]} [description]
	 */
	this.displayMobileSimpleNotifs = function(){
		let nbNotif = $("#simple_notification_bloc_inner > li").length;
		// We detach and store the content of the notification bloc.
		//-----------------------------------
		let liNotif = $("#simple_notification_bloc_inner > li").detach();

		let str = `
		<div id='btnDisplayPopupSimpleNotif'>
			<span class="fa-stack">
			  <i class="fa fa-bell"></i>
			  <i class="fa fa-exclamation-circle fa-stack-1x fa-new_icon fa-inverse"></i>
			</span>
		</div>

		<div id='popupSimpleNotifications' class='vpPopup' style='display:none;'>
			<i class='fa fa-times-circle ico_close_popup'></i>
			<div id='popupSimpleNotificationsList' class='popupContent'></div>
		</div>`;

		$("#simple_notification_bloc_inner").append(str);
		$("#simple_notification_bloc").show();

		liNotif.appendTo("#popupSimpleNotificationsList");

		$("#btnDisplayPopupSimpleNotif").click(function(event) {
			$("#popupSimpleNotifications").show();
		});
		$("#popupSimpleNotifications > .ico_close_popup").click(function(event) {
			$("#popupSimpleNotifications").hide();
		});
	}


	/*#########################################
	# >>	vp_SURVEY
	#########################################*/

	/**
	 * Display the wanted survey.
	 * @param  {[type]} surveyId [description]
	 * @param  {[type]} options  'notInPopup' (defauklt false);
	 * @return {[type]}          [description]
	 */
	this.displaySurvey = function(surveyId){
		
		let rand = randInt();
        // Options :
        //-----------------------------------
        if(typeof options === "undefined"){ options = "";}
    	var a = options.split(" ");
    	

    	$("body").append(`<div id='popup_${rand}'></div>`);
    	$("#popup_"+rand).load("plugins/vp_survey/01_display_survey.php?nc="+Math.random(),
				{survey_id:surveyId}, 
				function(){
					
    	});


	}


	/*#########################################
	# >>	DEV
	#########################################*/
	this.log = function(){
		console.log("uDEver -------");
		console.log(uDEver);

		console.log("uDDay -------");
		console.log(uDDay);
	}

}