How to use handler method in qawolf

Best JavaScript code snippet using qawolf

main.js

Source:main.js Github

copy

Full Screen

1"use strict";2(function()3{ 4 window.addEventListener("load", main);5}());6function main(){7 //player.setCookie("Henrique", 3, 100, 999,"11111","00");8 //player.setCookie("Carlos", 3, 99, 1000,"11000","00");9 //player.setCookie("Paulo", 2, 10, 20,"11000","00");10 //this way we can pass by reference11 //currentMenu used to remove liseners from the page where the menu appears12 var auxMisc = new GlobalVariables();13 //extra references to the DOM14 var domAux = new DomElements(15 document.getElementById("textPop"),16 document.getElementById("playerCredits"),17 document.getElementById("name"),18 document.getElementById("playerLevel"),19 document.getElementById("playerMain"),20 document.getElementById("playerLeaderBoard")21 )22 //load of the spaceships in the beggining to get the natural width and height23 var nToLoad = {"spaceship0": 5 , "spaceship1": 5 };24 var nLoaded = {"spaceship0": 0 , "spaceship1": 0 };25 var imgsMenu = {"spaceship0": [], "spaceship1": []};26 var imgs;27 var sounds;28 var musics;29 var player = new Player();30 //saves buttons reference to the DOM31 //this way we can add/remove listeners freely32 var buttons = {"pauseMenu": [], "startMenu" : [], "loginRegMenu": [], "popUpMenu" : [], "mainMenu" : [],"levelMenu": [], "chooseSpaceshipMenu": [], "leaderBoard" : [], "controlsMenu":[], "creditsMenu":[], "helpMenu":[] };33 //saves buttons reference to the DOM34 //this way we can do style.block and style.none to display and hide menus35 var menus = new Menus(document, auxMisc["menusArray"]);36 //used to change background colour37 var body = document.getElementsByTagName("body")[0];38 function initEndHandler(ev){39 window.removeEventListener("initEnd", initEndHandler);40 firstMenu(menus, auxMisc, musics, body);41 menuListeners(auxMisc, menus, buttons, imgs, sounds, musics, body, domSpaceships(menus), domAux, player);42 }43 function initSoundsEndHandler(ev){44 window.removeEventListener("initSoundsEnd", initSoundsEndHandler);45 window.addEventListener("initEnd", initEndHandler);46 calculateMonitorRefreshRate(auxMisc);47 }48 function initMusicsEndHandler(ev){49 window.removeEventListener("initMusicsEnd", initMusicsEndHandler);50 window.addEventListener("initSoundsEnd", initSoundsEndHandler);51 //load the sounds of the game52 nToLoad = {"rockets" : 1 , "buttons" : 2 ,"esc" : 2 };53 sounds = {"rockets" : [], "buttons" : [],"esc" : []};54 initSounds(nToLoad, sounds);55 }56 function initImagesEndHandler(ev){57 window.removeEventListener("initImagesEnd", initImagesEndHandler);58 window.addEventListener("initMusicsEnd", initMusicsEndHandler);59 //load the music of the game60 nToLoad = {"campain" : 3 ,"endless" : 1 , "boss" : 2 ,"music": 1 };61 musics = {"campain" : [],"endless" : [], "boss" : [],"music": []};62 initMusics(nToLoad, musics);63 }64 function initMenuEndHandler(ev){65 window.removeEventListener("initMenuEnd", initMenuEndHandler);66 window.addEventListener("initImagesEnd", initImagesEndHandler);67 //load the imagens of the game68 var nToLoad = { "spaceship" : 5 , "enemies" : 2 , "boss" : 2 , "asteroids" : 1 , "powerups" : 9 , "others" : 1, "rockets" : 1 , "enemyRockets" : 1 , "background" : 1 , "explosions" : 1 , "gameover" : 2 , "win" : 1 };69 var nLoaded = { "spaceship" : 0 , "enemies" : 0 , "boss" : 0 , "asteroids" : 0 , "powerups" : 0 , "others" : 0, "rockets" : 0 , "enemyRockets" : 0 , "background" : 0 , "explosions" : 0 , "gameover" : 0 , "win" : 0 };70 imgs = { "spaceship" : [], "enemies" : [], "boss" : [], "asteroids" : [], "powerups" : [], "others" : [],"rockets" : [], "enemyRockets" : [], "background" : [], "explosions" : [], "gameover" : [], "win" : []};71 72 initImages(nLoaded, nToLoad, imgs, imgsMenu);73 }74 window.addEventListener("initMenuEnd", initMenuEndHandler);75 76 initMenu(nLoaded, nToLoad, imgsMenu);77 //pause78 var muteM = document.getElementById("pauseMenu_0");79 buttons["pauseMenu"].push(muteM);80 var volumeLowM = document.getElementById("pauseMenu_1");81 buttons["pauseMenu"].push(volumeLowM);82 var volumeHighM = document.getElementById("pauseMenu_2");83 buttons["pauseMenu"].push(volumeHighM);84 85 var muteS = document.getElementById("pauseMenu_3");86 buttons["pauseMenu"].push(muteS);87 var volumeLowS = document.getElementById("pauseMenu_4");88 buttons["pauseMenu"].push(volumeLowS);89 var volumeHighS = document.getElementById("pauseMenu_5");90 buttons["pauseMenu"].push(volumeHighS);91 var back = document.getElementById("pauseMenu_6");92 buttons["pauseMenu"].push(back);93 //startMenu94 var startButon = document.getElementById("startMenu_0");95 buttons["startMenu"].push(startButon);96 //loginRegMenu97 var signUpButon = document.getElementById("loginRegMenu_0");98 buttons["loginRegMenu"].push(signUpButon);99 var loginButon = document.getElementById("loginRegMenu_1");100 buttons["loginRegMenu"].push(loginButon);101 //popUpMenu102 var yesButon = document.getElementById("popUpMenu_0");103 buttons["popUpMenu"].push(yesButon);104 var okButon = document.getElementById("popUpMenu_1");105 buttons["popUpMenu"].push(okButon);106 var noButon = document.getElementById("popUpMenu_2");107 buttons["popUpMenu"].push(noButon);108 //mainMenu109 var campain = document.getElementById("mainMenu_0");110 buttons["mainMenu"].push(campain);111 var endless = document.getElementById("mainMenu_1");112 buttons["mainMenu"].push(endless);113 var editor = document.getElementById("mainMenu_2");114 buttons["mainMenu"].push(editor);115 var leave = document.getElementById("mainMenu_3");116 buttons["mainMenu"].push(leave);117 var help = document.getElementById("mainMenu_4");118 buttons["mainMenu"].push(help);119 var credits = document.getElementById("mainMenu_5");120 buttons["mainMenu"].push(credits);121 var leaderBoard = document.getElementById("mainMenu_6");122 buttons["mainMenu"].push(leaderBoard);123 var controls = document.getElementById("mainMenu_7");124 buttons["mainMenu"].push(controls);125 //levelMenu126 var level1 = document.getElementById("levelMenu_0");127 buttons["levelMenu"].push(level1);128 var level2 = document.getElementById("levelMenu_1");129 buttons["levelMenu"].push(level2);130 var level3 = document.getElementById("levelMenu_2");131 buttons["levelMenu"].push(level3);132 var speedrun = document.getElementById("levelMenu_3");133 buttons["levelMenu"].push(speedrun);134 var back = document.getElementById("levelMenu_4");135 buttons["levelMenu"].push(back);136 //chooseSpaceshipMenu137 var left = document.getElementById("chooseSpaceshipMenu_0");138 buttons["chooseSpaceshipMenu"].push(left);139 var right = document.getElementById("chooseSpaceshipMenu_1");140 buttons["chooseSpaceshipMenu"].push(right);141 var go = document.getElementById("chooseSpaceshipMenu_2");142 buttons["chooseSpaceshipMenu"].push(go);143 var backChooseSpaceship = document.getElementById("chooseSpaceshipMenu_3");144 buttons["chooseSpaceshipMenu"].push(backChooseSpaceship);145 //creditsMenu146 var backCredits = document.getElementById("creditsMenu_0");147 buttons["creditsMenu"].push(backCredits);148 //helpMenu149 var backHelp = document.getElementById("helpMenu_0");150 buttons["helpMenu"].push(backHelp);151 var nextHelp = document.getElementById("helpMenu_1");152 buttons["helpMenu"].push(nextHelp);153 //controlsMenu154 var backControl = document.getElementById("controlsMenu_0");155 buttons["controlsMenu"].push(backControl);156 var nextControl = document.getElementById("controlsMenu_1");157 buttons["controlsMenu"].push(nextControl);158 var playControl = document.getElementById("controlsMenu_2");159 buttons["controlsMenu"].push(playControl);160 //leaderBoard161 var leaderBoardBack = document.getElementById("leaderBoard_0");162 buttons["leaderBoard"].push(leaderBoardBack);163}164function initMenu(nLoaded, nToLoad, imgsMenu){165 var numToLoad = 0;166 //Images load handler167 function imgMenuLoad(ev){168 var img = ev.target;169 let key = img.id.split("_")[0];170 nLoaded[key] += 1;171 if (allLoaded(nLoaded, numToLoad) == true){172 var evInitMenuEnd = new Event("initMenuEnd");173 window.dispatchEvent(evInitMenuEnd);174 }175 }176 for (let toLoad in nToLoad){177 numToLoad += nToLoad[toLoad];178 }179 for (let key in imgsMenu){180 for (var i = 0; i < nToLoad[key]; i++ ){181 imgsMenu[key][i] = new Image(); 182 imgsMenu[key][i].addEventListener("load", imgMenuLoad);183 imgsMenu[key][i].id = [key]+"_" + i;184 imgsMenu[key][i].src = "resources/menu/"+[key]+"_" + i + ".png"; //dá ordem de loadmento da imagem185 }186 }187}188function initImages(nLoaded, nToLoad, imgs, imgsMenu){189 var numToLoad = 0;190 //Images load handler191 function imgLoad(ev){192 var img = ev.target;193 let key = img.id.split("_")[0];194 nLoaded[key] += 1;195 if (allLoaded(nLoaded, numToLoad) == true){196 var evInitImagesEnd = new Event("initImagesEnd");197 imgs["imgsMenus"] = imgsMenu;198 window.dispatchEvent(evInitImagesEnd);199 }200 }201 for (let toLoad in nToLoad){202 numToLoad += nToLoad[toLoad];203 }204 for (let key in imgs){205 for (var i = 0; i < nToLoad[key]; i++ ){206 imgs[key][i] = new Image(); 207 imgs[key][i].addEventListener("load", imgLoad);208 imgs[key][i].id = [key]+"_" + i;209 imgs[key][i].src = "resources/game/"+[key]+"_" + i + ".png"; //dá ordem de loadmento da imagem210 }211 }212}213function initMusics(nToLoad, musics){214 for (let key in musics){215 for (var i = 0; i < nToLoad[key]; i++ ){216 musics[key][i] = new Audio();217 musics[key][i].id = [key]+"_" + i;218 musics[key][i].src = "resources/musics/"+[key]+"_" + i + ".mp3"; //dá ordem de loadmento da imagem219 }220 }221 var evInitEnd = new Event("initMusicsEnd");222 window.dispatchEvent(evInitEnd);223}224function initSounds(nToLoad, sounds){225 for (let key in sounds){226 for (var i = 0; i < nToLoad[key]; i++ ){227 sounds[key][i] = new Audio();228 sounds[key][i].id = [key]+"_" + i;229 sounds[key][i].src = "resources/sounds/"+[key]+"_" + i + ".mp3"; //dá ordem de loadmento da imagem230 }231 }232 var evInitEnd = new Event("initSoundsEnd");233 window.dispatchEvent(evInitEnd);234}235function calculateMonitorRefreshRate(auxMisc){236 var i = 0;237 var totalTime = 0;238 var oldtime = 0;239 var refreshRate;240 var oldRefreshRate = 0;241 var requestId;242 function aux(time){243 if(oldtime > 0){244 oldRefreshRate = refreshRate;245 refreshRate = Math.round(1000/(time - oldtime));246 if(refreshRate == oldRefreshRate){247 auxMisc["fps"] = refreshRate;248 window.cancelAnimationFrame(requestId);249 var evInitEnd = new Event("initEnd");250 window.dispatchEvent(evInitEnd);251 return;252 }253 }254 /*if(i > 0){255 totalTime += time - oldtime;256 257 if(i >= 5){258 auxMisc["fps"] = Math.round(1000/(totalTime/5));259 window.cancelAnimationFrame(requestId);260 var evInitEnd = new Event("initEnd");261 window.dispatchEvent(evInitEnd);262 return;263 }264 }265 i++;*/266 oldtime = time;267 requestId = window.requestAnimationFrame(aux);268 }269 requestId = window.requestAnimationFrame(aux);270}271function allLoaded(nLoaded,numToLoad){272 var sumLoaded = 0;273 for(let lo in nLoaded){274 sumLoaded += nLoaded[lo];275 }276 if(sumLoaded == numToLoad){277 return true;278 }else{279 return false;280 }281}282function menuListeners(auxMisc, menus, buttons, imgs, sounds, musics, body, spaceships, domAux, player){283 var auxKeyDownHandler = function(ev){284 KeyDownHandler(ev, buttons, menus, auxMisc, sounds, musics, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);285 }286 var auxClickHandler = function(ev){287 sounds["buttons"][1].load();288 sounds["buttons"][1].play().catch(function(){});289 290 //which button?291 switch(ev.target.id){292 //PAUSA--------------293 //mute294 case("pauseMenu_0"): 295 muteClickHandlerM(musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);296 break;297 case("pauseMenu_1"): 298 somLowClickHandlerM(musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);299 break;300 case("pauseMenu_2"):301 somHighClickHandlerM(musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);302 break;303 case("pauseMenu_3"): 304 muteClickHandlerS(sounds, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);305 break;306 case("pauseMenu_4"): 307 somLowClickHandlerS(sounds, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);308 break;309 case("pauseMenu_5"):310 somHighClickHandlerS(sounds, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);311 break;312 case("pauseMenu_6"):313 leaveDoGameClickHandler(auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux);314 break;315 //START------------316 case("startMenu_0"):317 startClickHandler(ev, menus, auxMisc);318 break;319 //LOGIN REG------------320 //signUp321 case("loginRegMenu_0"):322 signUpClickHandler(ev, menus, auxMisc, musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);323 break;324 //login325 case("loginRegMenu_1"):326 loginClickHandler(menus, auxMisc, musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);327 break;328 //POP UP------------329 //yes330 case("popUpMenu_0"):331 yesClickHandler(ev, menus, auxMisc, musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);332 break;333 //ok334 case("popUpMenu_1"):335 okClickHandler(ev, menus, auxMisc, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);336 break;337 //no338 case("popUpMenu_2"):339 noClickHandler(ev, menus, auxMisc, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);340 break;341 //MAIN MENU------------342 //campain343 case("mainMenu_0"): 344 campainClickHandler(ev, auxMisc, menus, domAux);345 break;346 //endless347 case("mainMenu_1"):348 endlessClickHandler(ev, auxMisc, menus, buttons, body, spaceships,imgs);349 break;350 case("mainMenu_2"):351 console.log("editor");352 break;353 //closes game354 case("mainMenu_3"): 355 closesGameClickHandler(ev, auxMisc, sounds, musics, menus, body); 356 break;357 //help358 case("mainMenu_4"):359 helpClickHandler(ev, menus, auxMisc, body);360 break;361 //credits362 case("mainMenu_5"): 363 creditsClickHandler(ev, menus, auxMisc, domAux);364 break;365 366 //leaderBoard367 case("mainMenu_6"): 368 leaderBoardClickHandler(ev, menus, auxMisc, body, domAux);369 break; 370 371 //controls372 case("mainMenu_7"): 373 controlsClickHandler(ev, menus, auxMisc, body);374 break; 375 //LEVEL MENU------------376 //level 1377 case("levelMenu_0"): 378 levelClickHandler(ev, auxMisc, menus, buttons, body, 1, spaceships, imgs);379 break;380 case("levelMenu_1"): 381 levelClickHandler(ev, auxMisc, menus, buttons, body, 2, spaceships, imgs);382 break;383 case("levelMenu_2"):384 levelClickHandler(ev, auxMisc, menus, buttons, body, 3, spaceships, imgs);385 break;386 case("levelMenu_3"):387 speedrunClickHandler(ev, auxMisc, menus, buttons, body, spaceships, imgs);388 break;389 //back390 case("levelMenu_4"):391 levelMenuBack(ev, menus, auxMisc);392 break;393 //CHOOSE SPACESHIP MENU------------394 //left395 case("chooseSpaceshipMenu_1"): 396 leftClickHandler(ev, auxMisc, menus, buttons, spaceships, imgs);397 break;398 //right399 case("chooseSpaceshipMenu_0"): 400 rightClickHandler(ev, auxMisc, menus, buttons, spaceships, imgs);401 break;402 //play403 case("chooseSpaceshipMenu_2"):404 playClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);405 break;406 //back407 case("chooseSpaceshipMenu_3"):408 chooseSpaceshipsMenuBack(ev, menus, auxMisc, body);409 break;410 //LEADERBOARD------------411 //back412 case("leaderBoard_0"):413 leaderBoardBackClickHandler(ev, menus, auxMisc, body);414 break;415 //CREDITS MENU------------416 //back417 case("creditsMenu_0"):418 creditsBackClickHandler(ev, menus, auxMisc);419 break;420 //CONTROLS MENU------------421 //back422 case("controlsMenu_0"):423 controlsBackClickHandler(ev, menus, auxMisc, body, buttons, player);424 break;425 case("controlsMenu_1"):426 controlsNextClickHandler(ev, menus, auxMisc, body, buttons, player);427 break; 428 case("controlsMenu_2"):429 controlsPlayClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);430 break;431 //HELP MENU------------432 //back433 case("helpMenu_0"):434 helpBackClickHandler(ev, menus, auxMisc, body, player);435 break;436 //next437 case("helpMenu_1"):438 helpPlayClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);439 break;440 }441 }442 var auxMouseInHandler = function(ev){443 let key = ev.target.id.split("_")[0];444 let index = ev.target.id.split("_")[1];445 buttons[key][index].style.opacity = 0.7;446 buttons[key][index].style.cursor = "pointer";447 sounds["buttons"][0].load();448 sounds["buttons"][0].play().catch(function(){});449 }450 var auxMouseOutHandler = function(ev){451 let key = ev.target.id.split("_")[0];452 let index = ev.target.id.split("_")[1];453 buttons[key][index].style.opacity = 1;454 buttons[key][index].style.cursor = "default";455 }456 //LISTENERS vvvvv457 window.addEventListener("keydown",auxKeyDownHandler); 458 //if he is coming from the game and he didnt unlock fillerText Henrique459 if (auxMisc["oldMenu"] == "chooseSpaceshipMenu" && menus["popUpMenu"].style.display == ""){460 for(let key in buttons){461 if(key != "pauseMenu"){462 for ( var i = 0; i < Object.keys(buttons[key]).length; i++){463 addEVLButtons(buttons, key, i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);464 }465 }466 }467 //beggining468 }else if(auxMisc["oldMenu"] == "fillerText"){469 for(let key in buttons){470 for ( var i = 0; i < Object.keys(buttons[key]).length; i++){471 addEVLButtons(buttons, key, i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);472 }473 }474 //if he is coming from a game and he unlocked a spaceship475 }else if(auxMisc["oldMenu"] == "chooseSpaceshipMenu" && menus["popUpMenu"].style.display == "block"){476 for(let key in buttons){477 if(key == "popUpMenu"){478 for ( var i = 0; i < Object.keys(buttons[key]).length; i++){479 addEVLButtons(buttons, key, i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);480 }481 }482 }483 }484 //LISTENERS ^^^^^^485}486function EnterPress( menus, auxMisc, musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux){487 if(auxMisc["currentMenu"] == "loginRegMenu"){488 loginClickHandler( menus, auxMisc, musics, buttons, auxClickHandler,auxMouseInHandler,auxMouseOutHandler, body, domAux)489 }490}491//Handlers vvvvvv492function KeyDownHandler(ev, buttons, menus, auxMisc, sounds, musics, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player){493 switch(ev.code) {494 case "Escape": togglePauseMenu(buttons, menus, auxMisc, sounds, musics, auxClickHandler, auxMouseInHandler, auxMouseOutHandler); break;495 case "Enter": EnterPress(menus, auxMisc, musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux); break;496 case "KeyP":497 auxMisc["secretProgress"] += "P";498 if(auxMisc["secretPress"].indexOf(auxMisc["secretProgress"]) != 0){499 auxMisc["secretProgress"] = "P";500 }501 else if(auxMisc["secretPress"] == auxMisc["secretProgress"]){502 var unlockingSpaceship = 4;503 unlockSpaceship(unlockingSpaceship, auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux, player);504 }505 break;506 default: secret(ev, auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux, player);break;507 508 }509}510// PAUSE -------511function muteClickHandlerM(musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){512 for(let key in musics){513 for ( let i = 0; i < Object.keys(musics[key]).length; i++){514 musics[key][i].volume = 0;515 }516 }517 518 buttons["pauseMenu"][0].style.opacity = 0.3;519 buttons["pauseMenu"][0].style.cursor = "default";520 removeEVLButtons(buttons, "pauseMenu", 0, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);521 522 buttons["pauseMenu"][1].style.opacity = 0.3;523 buttons["pauseMenu"][1].style.cursor = "default";524 removeEVLButtons(buttons, "pauseMenu", 1, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);525 //sound goes from 1 to 0526 buttons["pauseMenu"][2].style.opacity = 1;527 addEVLButtons(buttons, "pauseMenu", 2, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);528}529function somLowClickHandlerM(musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){530 console.log("-M"); 531 532 //place volume up button again533 if (musics["music"][0].volume + 0.2 > 1){534 buttons["pauseMenu"][2].style.opacity = 1;535 addEVLButtons(buttons, "pauseMenu", 2, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);536 }537 for(let key in musics){538 for ( let i = 0; i < Object.keys(musics[key]).length; i++){539 musics[key][i].volume -= 0.2;540 }541 }542 //turn of mute and volume down buttons543 if (musics["music"][0].volume - 0.2 < 0 ){544 buttons["pauseMenu"][0].style.opacity = 0.3;545 buttons["pauseMenu"][0].style.cursor = "default";546 removeEVLButtons(buttons, "pauseMenu", 0, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);547 buttons["pauseMenu"][1].style.opacity = 0.3;548 buttons["pauseMenu"][1].style.cursor = "default";549 removeEVLButtons(buttons, "pauseMenu", 1, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);550 }551}552function somHighClickHandlerM(musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){553 console.log("+M"); 554 //place volume down and mute buttons again555 if (musics["music"][0].volume - 0.2 < 0 ){556 buttons["pauseMenu"][0].style.opacity = 1;557 addEVLButtons(buttons, "pauseMenu", 0, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);558 buttons["pauseMenu"][1].style.opacity = 1;559 addEVLButtons(buttons, "pauseMenu", 1, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);560 }561 for(let key in musics){562 for ( let i = 0; i < Object.keys(musics[key]).length; i++){563 musics[key][i].volume += 0.2;564 }565 }566 //turn off volume up button567 if (musics["music"][0].volume + 0.2 > 1){568 buttons["pauseMenu"][2].style.opacity = 0.3;569 buttons["pauseMenu"][2].style.cursor = "default";570 removeEVLButtons(buttons, "pauseMenu", 2, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);571 }572}573function muteClickHandlerS(sounds, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){ 574 for(let key in sounds){575 for ( let i = 0; i < Object.keys(sounds[key]).length; i++){576 sounds[key][i].volume = 0;577 }578 }579 buttons["pauseMenu"][3].style.opacity = 0.3;580 buttons["pauseMenu"][3].style.cursor = "default";581 removeEVLButtons(buttons, "pauseMenu", 3, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);582 buttons["pauseMenu"][4].style.opacity = 0.3;583 buttons["pauseMenu"][4].style.cursor = "default";584 removeEVLButtons(buttons, "pauseMenu", 4, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);585 //sound goes from 1 to 0586 buttons["pauseMenu"][5].style.opacity = 1;587 addEVLButtons(buttons, "pauseMenu", 5, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);588}589function somLowClickHandlerS(sounds, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){590 console.log("-S"); 591 592 //place volume up button again593 if (sounds["buttons"][0].volume + 0.2 > 1){594 buttons["pauseMenu"][5].style.opacity = 1;595 addEVLButtons(buttons, "pauseMenu", 5, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);596 }597 for(let key in sounds){598 for ( let i = 0; i < Object.keys(sounds[key]).length; i++){599 sounds[key][i].volume -= 0.2;600 }601 }602 //turn of mute and volume down buttons603 if (sounds["buttons"][0].volume - 0.2 < 0 ){604 buttons["pauseMenu"][4].style.opacity = 0.3;605 buttons["pauseMenu"][4].style.cursor = "default";606 removeEVLButtons(buttons, "pauseMenu", 4, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);607 buttons["pauseMenu"][3].style.opacity = 0.3;608 buttons["pauseMenu"][3].style.cursor = "default";609 removeEVLButtons(buttons, "pauseMenu", 3, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);610 }611}612function somHighClickHandlerS(sounds, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){613 //place mute and volume down buttons again614 if (sounds["buttons"][0].volume - 0.2 < 0 ){615 buttons["pauseMenu"][3].style.opacity = 1;616 addEVLButtons(buttons, "pauseMenu", 3, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);617 buttons["pauseMenu"][4].style.opacity = 1;618 addEVLButtons(buttons, "pauseMenu", 4, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);619 }620 for(let key in sounds){621 for ( let i = 0; i < Object.keys(sounds[key]).length; i++){622 sounds[key][i].volume += 0.2;623 }624 }625 //turn off volume up button626 if (sounds["buttons"][0].volume + 0.2 > 1){627 buttons["pauseMenu"][5].style.opacity = 0.3;628 buttons["pauseMenu"][5].style.cursor = "default";629 removeEVLButtons(buttons, "pauseMenu", 5, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);630 }631}632function leaveDoGameClickHandler(auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux){633 //var text = document.getElementById("textPop");634 var text = domAux["textPop"];635 text.innerHTML = "Quere voltar ao menu principal??"636 buttons["popUpMenu"][0].style.display = "block";637 buttons["popUpMenu"][1].style.display = "none";638 buttons["popUpMenu"][2].style.display = "block";639 640 menus["popUpMenu"].style.display = "block";641 642 menus["popUpMenu"].style.zIndex = 4;643 //add listeners644 /*for (var i = 0 ; i < buttons["popUpMenu"].length; i++){645 addEVLButtons(buttons, "popUpMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler); 646 buttons["popUpMenu"][i].style.opacity = 1;647 }*/648 //REMOVE BUTTONS EVENTLISTENNERS649 //remove button ev listener that were left650 //doesn't change opacity so we know which have to get the ev listeners back651 for (var i = 0 ; i < buttons["pauseMenu"].length; i++){652 if (buttons["pauseMenu"][i].style.opacity == 1 || i == 6){653 removeEVLButtons(buttons, "pauseMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);654 }655 }656 buttons["pauseMenu"][6].style.opacity = 0.3;657}658//START------659function startClickHandler(ev, menus, auxMisc){660 menus["startMenu"].style.display = "";661 menus["loginRegMenu"].style.display = "block";662 auxMisc["currentMenu"] = "loginRegMenu";663 auxMisc["oldMenu"] = "startMenu";664}665//LOGIN REG------666function loginClickHandler(menus, auxMisc, musics, buttons, auxClickHandler,auxMouseInHandler,auxMouseOutHandler, body, domAux, player){667 //var name = document.getElementById("name").value;668 var name = domAux["name"].value;669 //name doesn't exist -> PopUp670 if(checkCookie(name) == false){671 672 //var text = document.getElementById("textPop");673 var text = domAux["textPop"];674 text.innerHTML = "There isn't an account with that username."675 buttons["popUpMenu"][0].style.display = "none";676 buttons["popUpMenu"][1].style.display = "block";677 buttons["popUpMenu"][2].style.display = "none";678 679 menus["popUpMenu"].style.display = "block";680 //REMOVE BUTTONS EVENTLISTENNERS681 for (var i = 0 ; i < buttons["loginRegMenu"].length; i++){682 removeEVLButtons(buttons, "loginRegMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);683 buttons["loginRegMenu"][i].style.opacity = 1;684 }685 }else{686 player.name = name;687 player.getCookie();688 login(name, menus, auxMisc, musics, body, buttons, domAux, player);689 }690 691}692function signUpClickHandler(ev, menus, auxMisc, musics, buttons, auxClickHandler,auxMouseInHandler,auxMouseOutHandler, body, domAux, player){693 694 //var name = document.getElementById("name").value;695 var name = domAux["name"].value;696 //invalid name697 if( name.indexOf("Level") != -1 ||698 name.indexOf("Campain") != -1 ||699 name.indexOf("Endless") != -1 ||700 name.indexOf("Spaceships") != -1 ||701 name.indexOf("Tutorial") != -1 ||702 name.indexOf(" ") != -1 ||703 name == ""){704 //var text = document.getElementById("textPop");705 var text = domAux["textPop"];706 text.innerHTML = "Invalid Username. Keep in mind your name can't be empty, contain spaces or the words: \"Level\", \"Campain\", \"Endless\", \"Spaceships\" and \"Tutorial\"";707 buttons["popUpMenu"][0].style.display = "none";708 buttons["popUpMenu"][1].style.display = "block";709 buttons["popUpMenu"][2].style.display = "none";710 711 menus["popUpMenu"].style.display = "block";712 //REMOVE BUTTONS EVENTLISTENNERS713 for (var i = 0 ; i < buttons["loginRegMenu"].length; i++){714 removeEVLButtons(buttons, "loginRegMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);715 buttons["loginRegMenu"][i].style.opacity = 1;716 }717 //username already exists -> PopUp718 }else if(checkCookie(name) == true){719 //var text = document.getElementById("textPop");720 var text = domAux["textPop"];721 text.innerHTML = "This username has saved progress. Are you sure you want to erase it?"722 buttons["popUpMenu"][0].style.display = "block";723 buttons["popUpMenu"][1].style.display = "none";724 buttons["popUpMenu"][2].style.display = "block";725 726 menus["popUpMenu"].style.display = "block";727 //REMOVE BUTTONS EVENTLISTENNERS728 for (var i = 0 ; i < buttons["loginRegMenu"].length; i++){729 removeEVLButtons(buttons, "loginRegMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);730 buttons["loginRegMenu"][i].style.opacity = 1;731 }732 }else{733 player.createPlayer(name);734 login(name, menus, auxMisc, musics, body, buttons, domAux, player);735 }736}737//POP UP------738function yesClickHandler(ev, menus, auxMisc, musics, buttons, auxClickHandler,auxMouseInHandler,auxMouseOutHandler, body, domAux, player){739 menus["popUpMenu"].style.display = "";740 menus["popUpMenu"].style.zIndex = 1;741 //if the popup is on Log Reg Menu742 if (auxMisc["currentMenu"] == "loginRegMenu"){743 744 //var name = document.getElementById("name").value;745 var name = domAux["name"].value;746 player.createPlayer(name);747 login(name, menus, auxMisc, musics, body, buttons, domAux, player);748 //Reset Listeners749 for (var i = 0 ; i < buttons["loginRegMenu"].length; i++){750 addEVLButtons(buttons, "loginRegMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);751 }752 }753 //if the popup appears during a game754 else{755 /*buttons["pauseMenu"][6].style.opacity = 1;756 for (var i = 0 ; i < buttons["pauseMenu"].length; i++){757 if (buttons["pauseMenu"][i].style.opacity == 1 ){758 addEVLButtons(buttons, "pauseMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);759 }760 }761 //Code to get back to the menu (Henrique)762 763 */764 }765}766function okClickHandler(ev, menus, auxMisc, buttons, auxClickHandler,auxMouseInHandler,auxMouseOutHandler){767 menus["popUpMenu"].style.display = ""; 768 menus["popUpMenu"].style.zIndex = 1;769 //if the PopUpMenu has style.display = "block" and the user came from a game770 //this means he unlocked something ingame.771 if(auxMisc["oldMenu"] == "algumGame;_;"){772 for(let key in buttons){773 if(key != "pauseMenu" || key != "popUpMenu" ){774 for (var i = 0; i < Object.keys(buttons[key]).length; i++){775 addEVLButtons(buttons, key, i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);776 }777 }778 }779 //else if (auxMisc["currentMenu"] == "loginRegMenu" || auxMisc["currentMenu"] == "mainMenu"){780 }//if the PopUpMemu is on the Log Reg Menu or MainMenu781 else{782 //Reset Listeners783 for (var i = 0 ; i < buttons[auxMisc["currentMenu"]].length; i++){784 addEVLButtons(buttons, auxMisc["currentMenu"], i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);785 }786 }787}788function noClickHandler(ev, menus, auxMisc,buttons, auxClickHandler,auxMouseInHandler,auxMouseOutHandler){789 menus["popUpMenu"].style.display = ""; 790 menus["popUpMenu"].style.zIndex = 1;791 //if the PopUpMemu is on the Log Reg Menu792 if (auxMisc["currentMenu"] == "loginRegMenu"){793 //Reset listeners794 for (var i = 0 ; i < buttons["loginRegMenu"].length; i++){795 addEVLButtons(buttons, "loginRegMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);796 }797 //if the PopUpMemu appears while ingame (Henrique)798 }else{799 /*buttons["pauseMenu"][6].style.opacity = 1;800 for (var i = 0 ; i < buttons["pauseMenu"].length; i++){801 if (buttons["pauseMenu"][i].style.opacity == 1 ){802 addEVLButtons(buttons, "pauseMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);803 }804 }*/805 }806}807//MAIN MENU------808function campainClickHandler(ev, auxMisc, menus, domAux){809 menus["mainMenu"].style.display = "";810 menus["levelMenu"].style.display = "block";811 auxMisc["currentMenu"] = "levelMenu";812 auxMisc["oldMenu"] = "mainMenu";813 var name = auxMisc["playerAtual"];814 console.log(name);815 //document.getElementById("playerLevel").innerHTML = name;816 domAux["playerLevel"].innerHTM = name;817}818function endlessClickHandler(ev, auxMisc, menus, buttons, body, spaceships,imgs){819 body.bgColor = "#0a131f";820 menus["mainMenu"].style.display = "";821 menus["chooseSpaceshipMenu"].style.display = "block";822 auxMisc["currentMenu"] = "chooseSpaceshipMenu";823 auxMisc["oldMenu"] = "mainMenu";824 auxMisc["gamemode"] = "endless";825 putCorrectSpaceships(auxMisc, menus, buttons, spaceships,imgs);826}827function playEndlessClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player){828 body.bgColor = "black";829 menus["chooseSpaceshipMenu"].style.display = "";830 menus["canvasFigure"].style.display = "block";831 832 auxMisc["currentMenu"] = "endless";833 auxMisc["oldMenu"] = "chooseSpaceshipMenu";834 removeEventListeners(buttons, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);835 new Game(auxMisc, menus, buttons, imgs, sounds, musics, body, domAux, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, -1, player);836}837function closesGameClickHandler(ev, auxMisc, sounds, musics, menus, body){838 menus["mainMenu"].style.display = "";839 firstMenu(menus, auxMisc, musics, body);840}841function creditsClickHandler(ev, menus, auxMisc, domAux){842 menus["mainMenu"].style.display = "";843 menus["creditsMenu"].style.display = "block";844 auxMisc["currentMenu"] = "creditsMenu";845 auxMisc["oldMenu"] = "mainMenu";846 var name = auxMisc["playerAtual"];847 //document.getElementById("playerCredits").innerHTML = name;848 domAux["playerCredits"].innerHTML = name;849}850function helpClickHandler(ev, menus, auxMisc, body){851 body.bgColor = "#0a131f";852 menus["mainMenu"].style.display = "";853 menus["helpMenu"].style.display = "block";854 auxMisc["currentMenu"] = "helpMenu";855 auxMisc["oldMenu"] = "mainMenu";856}857function leaderBoardClickHandler(ev, menus, auxMisc, body, domAux){858 body.bgColor = "#0a131f";859 menus["mainMenu"].style.display = "";860 menus["leaderBoard"].style.display = "block";861 auxMisc["currentMenu"] = "leaderBoard";862 auxMisc["oldMenu"] = "mainMenu";863 var name = auxMisc["playerAtual"];864 //document.getElementById("playerLeaderBoard").innerHTML = name;865 domAux["playerLeaderBoard"].innerHTML = name;866}867function controlsClickHandler(ev, menus, auxMisc, body){868 body.bgColor = "#0a131f";869 menus["mainMenu"].style.display = "";870 menus["controlsMenu"].style.display = "block";871 auxMisc["currentMenu"] = "controlsMenu";872 auxMisc["oldMenu"] = "mainMenu";873}874//NIVEL MENU-------875function levelClickHandler(ev, auxMisc, menus, buttons, body, level, spaceships, imgs){876 body.bgColor = "#0a131f";877 menus["levelMenu"].style.display = "";878 menus["chooseSpaceshipMenu"].style.display = "block";879 auxMisc["currentMenu"] = "chooseSpaceshipMenu";880 auxMisc["oldMenu"] = "levelMenu";881 auxMisc["gamemode"] = "level_" + level;882 putCorrectSpaceships(auxMisc, menus, buttons, spaceships, imgs);883}884function speedrunClickHandler(ev, auxMisc, menus, buttons, body, spaceships, imgs){885 body.bgColor = "#0a131f";886 menus["levelMenu"].style.display = "";887 menus["chooseSpaceshipMenu"].style.display = "block";888 auxMisc["currentMenu"] = "chooseSpaceshipMenu";889 auxMisc["oldMenu"] = "levelMenu";890 auxMisc["gamemode"] = "speedrun";891 putCorrectSpaceships(auxMisc, menus, buttons, spaceships, imgs);892}893function levelMenuBack(ev,menus,auxMisc){894 menus["levelMenu"].style.display = "";895 menus["mainMenu"].style.display = "block";896 auxMisc["currentMenu"] = "mainMenu";897 auxMisc["oldMenu"] = "levelMenu";898}899//CHOOSE SPACESHIP MENU-------900function playClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player){901 //hasn't seen the controls menu902 if(auxMisc["cookieStore"]["Tutorial"][0] == "0"){903 //appears Controls904 body.bgColor = "#0a131f";905 menus["chooseSpaceshipMenu"].style.display = "";906 menus["controlsMenu"].style.display = "block";907 908 auxMisc["currentMenu"] = "controlsMenu";909 auxMisc["oldMenu"] = "chooseSpaceshipMenu";910 //checks if the user knows the Help menu911 if(auxMisc["cookieStore"]["Tutorial"][1] == "0" ){912 //buttonNext913 buttons["controlsMenu"][1].style.display = "block";914 }else{915 //buttonPlay916 buttons["controlsMenu"][2].style.display = "block";917 }918 //hasn't seen the help menu <=> Tutorial[1] == "0"919 }else if (auxMisc["cookieStore"]["Tutorial"] == "10"){920 921 //appears Help922 body.bgColor = "#0a131f";923 menus["chooseSpaceshipMenu"].style.display = "";924 menus["helpMenu"].style.display = "block";925 926 auxMisc["oldMenu"] = "chooseSpaceshipMenu";927 auxMisc["currentMenu"] = "helpMenu";928 //appears buttons 929 buttons["helpMenu"][1].style.display = "block";930 931 //user knows controls and help menus932 }else if (auxMisc["cookieStore"]["Tutorial"] == "11"){933 var gamemode = auxMisc["gamemode"].split("_")[0]; 934 buttons["helpMenu"][1].style.display = "";935 buttons["controlsMenu"][1].style.display = "";936 buttons["controlsMenu"][2].style.display = "";937 if ( gamemode== "level"){938 playLevelClickHandler(ev, auxMisc, menus, buttons, imgs, sounds,musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, parseInt(auxMisc["gamemode"].split("_")[1]), domAux, player);939 }940 else if (gamemode == "speedrun"){941 playSpeedrunClickHandler(ev, auxMisc, menus, buttons, imgs, sounds,musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);942 }943 else if (gamemode == "endless"){944 playEndlessClickHandler(ev, auxMisc, menus, buttons, imgs, sounds,musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);945 }946 }947}948function playLevelClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, level, domAux, player){949 body.bgColor = "black";950 menus["chooseSpaceshipMenu"].style.display = "";951 menus["canvasFigure"].style.display = "block";952 953 auxMisc["currentMenu"] = "level" + level + "Menu";954 auxMisc["oldMenu"] = "chooseSpaceshipMenu";955 removeEventListeners(buttons, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);956 new Game(auxMisc, menus, buttons, imgs, sounds, musics, body, domAux, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, level, player);957}958function playSpeedrunClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player){959 body.bgColor = "black";960 menus["chooseSpaceshipMenu"].style.display = "";961 menus["canvasFigure"].style.display = "block";962 963 auxMisc["currentMenu"] = "speedrun";964 auxMisc["oldMenu"] = "chooseSpaceshipMenu";965 removeEventListeners(buttons, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);966 new Game(auxMisc, menus, buttons, imgs, sounds, musics, body, domAux, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, 0, player);967}968function rightClickHandler(ev, auxMisc, menus, buttons, spaceships, imgs){969 //var data = player.getCookie(auxMisc["playerAtual"]);970 var spaceshipsUser = auxMisc["cookieStore"]["Spaceships"];971 var spaceshipAntiga = auxMisc["currentSpaceship"];972 auxMisc["currentSpaceship"] = myMod(auxMisc["currentSpaceship"] -1, spaceshipsUser.length); 973 var appears_left = myMod(auxMisc["currentSpaceship"] - 1,spaceshipsUser.length);974 var right = spaceshipAntiga;975 var leave_right = myMod(auxMisc["currentSpaceship"] + 2, spaceshipsUser.length);976 auxChangeSpaceships(menus, buttons,spaceships,imgs, spaceshipsUser, spaceshipAntiga, appears_left, auxMisc["currentSpaceship"], right, leave_right);977}978function leftClickHandler(ev, auxMisc, menus, buttons, spaceships, imgs){979 //var data = player.getCookie(auxMisc["playerAtual"]);980 var spaceshipsUser = auxMisc["cookieStore"]["Spaceships"];981 982 var spaceshipAntiga = auxMisc["currentSpaceship"];983 auxMisc["currentSpaceship"] = myMod(auxMisc["currentSpaceship"] + 1, spaceshipsUser.length); 984 var leave_left = myMod(auxMisc["currentSpaceship"] - 2,spaceshipsUser.length);985 var left = spaceshipAntiga;986 var appears_right = myMod(auxMisc["currentSpaceship"] + 1, spaceshipsUser.length);987 auxChangeSpaceships(menus, buttons,spaceships,imgs, spaceshipsUser, spaceshipAntiga, left, auxMisc["currentSpaceship"], appears_right, leave_left);988}989function chooseSpaceshipsMenuBack(ev, menus, auxMisc, body){990 menus["chooseSpaceshipMenu"].style.display = "";991 body.bgColor = "#00081d";992 if( auxMisc["gamemode"] != "endless" ){993 menus["levelMenu"].style.display = "block";994 auxMisc["currentMenu"] = "levelMenu";995 }else{996 menus["mainMenu"].style.display = "block";997 998 auxMisc["currentMenu"] = "mainMenu";999 }1000 auxMisc["oldMenu"] = "chooseSpaceshipMenu";1001}1002//LEADERBOARD------1003function leaderBoardBackClickHandler(ev, menus, auxMisc, body){1004 body.bgColor = "#00081d";1005 menus["leaderBoard"].style.display = "";1006 menus["mainMenu"].style.display = "block";1007 auxMisc["currentMenu"] = "mainMenu";1008 auxMisc["oldMenu"] = "leaderBoard";1009}1010//CREDITOS MENU------1011function creditsBackClickHandler(ev, menus, auxMisc){1012 menus["creditsMenu"].style.display = "";1013 menus["mainMenu"].style.display = "block";1014 1015 auxMisc["currentMenu"] = "mainMenu";1016 auxMisc["oldMenu"] = "creditsMenu";1017}1018//CONTROLOS MENU -----1019function controlsBackClickHandler(ev, menus, auxMisc,body, buttons, player){1020 1021 menus["controlsMenu"].style.display = "";1022 buttons["controlsMenu"][1].style.display = "";1023 buttons["controlsMenu"][2].style.display = "";1024 //user already saw the Controls menu1025 auxMisc["cookieStore"]["Tutorial"] = "1"+auxMisc["cookieStore"]["Tutorial"][1];1026 player.updateCoockiesTutorial(auxMisc,"1"+auxMisc["cookieStore"]["Tutorial"][1]);1027 if(auxMisc["oldMenu"] == "mainMenu"){1028 body.bgColor = "#00081d";1029 menus["mainMenu"].style.display = "block";1030 auxMisc["currentMenu"] = "mainMenu";1031 auxMisc["oldMenu"] = "controlsMenu";1032 }else{1033 body.bgColor = "#0a131f";1034 menus["chooseSpaceshipMenu"].style.display = "block";1035 auxMisc["currentMenu"] = "chooseSpaceshipMenu";1036 auxMisc["oldMenu"] = "controlsMenu";1037 1038 buttons["helpMenu"][1].style.display = "";1039 }1040}1041function controlsNextClickHandler(ev, menus, auxMisc, body, buttons, player){1042 body.bgColor = "#0a131f";1043 menus["controlsMenu"].style.display = "";1044 menus["helpMenu"].style.display = "block";1045 auxMisc["currentMenu"] = "helpMenu";1046 auxMisc["oldMenu"] = "controlsMenu";1047 auxMisc["cookieStore"]["Tutorial"] = "1"+auxMisc["cookieStore"]["Tutorial"][1] ;1048 player.updateCoockiesTutorial(auxMisc,"1"+auxMisc["cookieStore"]["Tutorial"][1]);1049 buttons["helpMenu"][1].style.display = "block";1050}1051function controlsPlayClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player){1052 menus["controlsMenu"].style.display = "";1053 1054 //user already saw the Controls menu1055 auxMisc["cookieStore"]["Tutorial"] = "1"+auxMisc["cookieStore"]["Tutorial"][1] ;1056 player.updateCoockiesTutorial(auxMisc,"1"+auxMisc["cookieStore"]["Tutorial"][1]);1057 playClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);1058}1059//HELP MENU------1060function helpBackClickHandler(ev, menus, auxMisc, body, player){1061 //goes to the old menu1062 //if Tutorial[1] == 1 goes to mainMenu;1063 //if Tutorial[1] == 0 goes to controls or chooseSpaceshipsMenu1064 if(auxMisc["oldMenu"] == "mainMenu"){1065 body.bgColor = "#00081d";1066 }else{1067 body.bgColor = "#0a131f";1068 }1069 menus["helpMenu"].style.display = "";1070 menus[auxMisc["oldMenu"]].style.display = "block";1071 auxMisc["currentMenu"] = auxMisc["oldMenu"];1072 auxMisc["oldMenu"] = "helpMenu";1073 1074 //user already saw the Help menu1075 auxMisc["cookieStore"]["Tutorial"] = auxMisc["cookieStore"]["Tutorial"][0]+"1" ;1076 player.updateCoockiesTutorial(auxMisc, auxMisc["cookieStore"]["Tutorial"][0]+"1");1077}1078function helpPlayClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player){1079 menus["helpMenu"].style.display = "";1080 1081 //user already saw the Help menu1082 auxMisc["cookieStore"]["Tutorial"] = auxMisc["cookieStore"]["Tutorial"][0]+"1" ;1083 player.updateCoockiesTutorial(auxMisc, auxMisc["cookieStore"]["Tutorial"][0]+"1");1084 playClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);1085}1086//Handlers ^^^^^^1087//Aux Functions vvvvvvvv1088function secret(ev, auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux, player){1089 var unlockingSpaceship = 4;1090 //checks if he is on the mainMenu, if he still doesn't have the spaceship and if the popUp menu isn't open1091 if(auxMisc["currentMenu"] == "mainMenu" && menus["pauseMenu"].style.display == "" && auxMisc["cookieStore"]["Spaceships"][unlockingSpaceship] != "1" && menus["popUpMenu"].style.display == ""){1092 auxMisc["secretProgress"] += ev.code.substring(3);1093 if(auxMisc["secretPress"] == auxMisc["secretProgress"]){1094 unlockSpaceship(unlockingSpaceship, auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux, player); 1095 }1096 }1097}1098function unlockSpaceship(unlockingSpaceship, auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux, player){1099 var spaceshipsStr = "";1100 //update spaceships 1101 player.updateCoockiesSpaceships(auxMisc,unlockingSpaceship);1102 for(var i = 0; i < auxMisc["cookieStore"]["Spaceships"].length; i++){1103 if(i == unlockingSpaceship){1104 spaceshipsStr += "1";1105 }else{1106 spaceshipsStr += auxMisc["cookieStore"]["Spaceships"][i];1107 }1108 }1109 auxMisc["cookieStore"]["Spaceships"] = spaceshipsStr;1110 //var text = document.getElementById("textPop");1111 var text = domAux["textPop"];1112 text.innerHTML = "Congratulations you unlocked spaceship number "+ unlockingSpaceship;1113 buttons["popUpMenu"][0].style.display = "none";1114 buttons["popUpMenu"][1].style.display = "block";1115 buttons["popUpMenu"][2].style.display = "none";1116 1117 menus["popUpMenu"].style.display = "block";1118 //REMOVE BUTTONS EVENTLISTENNERS1119 for (var i = 0 ; i < buttons["mainMenu"].length; i++){1120 buttons["mainMenu"][i].removeEventListener("click",auxClickHandler);1121 buttons["mainMenu"][i].removeEventListener("mouseover",auxMouseInHandler);1122 buttons["mainMenu"][i].removeEventListener("mouseout",auxMouseOutHandler); 1123 buttons["mainMenu"][i].style.opacity = 1;1124 }1125}1126function unlocksSpaceshipByLevel(levelCompletado, auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux, player){1127 switch(levelCompletado){ 1128 case(2): unlockSpaceship(3, auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux, player);break;1129 case(-11): unlockSpaceship(2, auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux, player);break;1130 }1131}1132function playSound(musics, level){1133 //play every music1134 for(let key in musics){1135 for ( let i = 0; i < Object.keys(musics[key]).length; i++){1136 musics[key][i].pause();1137 musics[key][i].currentTime = 0;1138 }1139 }1140 //endless1141 if(level == -1){1142 musics["endless"][0].loop = true;1143 musics["endless"][0].load();1144 musics["endless"][0].play().catch(function(){});1145 //campain1146 }else{1147 musics["campain"][level - 1].loop = true;1148 musics["campain"][level - 1].load();1149 musics["campain"][level - 1].play().catch(function(){});1150 }1151}1152function updateSoundButton(sounds, musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){1153 //max Sound Volume1154 if(sounds["buttons"][0].volume + 0.2 > 1){1155 buttons["pauseMenu"][5].style.opacity = 0.3; 1156 1157 buttons["pauseMenu"][5].removeEventListener("click",auxClickHandler);1158 buttons["pauseMenu"][5].removeEventListener("mouseover",auxMouseInHandler);1159 buttons["pauseMenu"][5].removeEventListener("mouseout",auxMouseOutHandler); 1160 1161 //min Sound Volume1162 }else if (sounds["buttons"][0].volume - 0.2 < 0){1163 buttons["pauseMenu"][3].style.opacity = 0.3; 1164 1165 buttons["pauseMenu"][3].removeEventListener("click",auxClickHandler);1166 buttons["pauseMenu"][3].removeEventListener("mouseover",auxMouseInHandler);1167 buttons["pauseMenu"][3].removeEventListener("mouseout",auxMouseOutHandler); 1168 buttons["pauseMenu"][4].style.opacity = 0.3; 1169 1170 buttons["pauseMenu"][4].removeEventListener("click",auxClickHandler);1171 buttons["pauseMenu"][4].removeEventListener("mouseover",auxMouseInHandler);1172 buttons["pauseMenu"][4].removeEventListener("mouseout",auxMouseOutHandler); 1173 }1174 //max Music Volume1175 if(musics["music"][0].volume + 0.2 > 1){1176 buttons["pauseMenu"][2].style.opacity = 0.3; 1177 1178 buttons["pauseMenu"][2].removeEventListener("click",auxClickHandler);1179 buttons["pauseMenu"][2].removeEventListener("mouseover",auxMouseInHandler);1180 buttons["pauseMenu"][2].removeEventListener("mouseout",auxMouseOutHandler); 1181 1182 //min Music Volume1183 }else if (musics["music"][0].volume - 0.2 < 0){1184 buttons["pauseMenu"][0].style.opacity = 0.3; 1185 1186 buttons["pauseMenu"][0].removeEventListener("click",auxClickHandler);1187 buttons["pauseMenu"][0].removeEventListener("mouseover",auxMouseInHandler);1188 buttons["pauseMenu"][0].removeEventListener("mouseout",auxMouseOutHandler); 1189 buttons["pauseMenu"][1].style.opacity = 0.3; 1190 1191 buttons["pauseMenu"][1].removeEventListener("click",auxClickHandler);1192 buttons["pauseMenu"][1].removeEventListener("mouseover",auxMouseInHandler);1193 buttons["pauseMenu"][1].removeEventListener("mouseout",auxMouseOutHandler); 1194 }1195}1196function addEVLButtons(buttons, key, i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){1197 buttons[key][i].addEventListener("click", auxClickHandler);1198 buttons[key][i].addEventListener("mouseover", auxMouseInHandler);1199 buttons[key][i].addEventListener("mouseout", auxMouseOutHandler);1200}1201function removeEVLButtons(buttons, key, i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){1202 buttons[key][i].removeEventListener("click", auxClickHandler);1203 buttons[key][i].removeEventListener("mouseover", auxMouseInHandler);1204 buttons[key][i].removeEventListener("mouseout", auxMouseOutHandler);1205}1206function auxChangeSpaceships(menus, buttons, spaceships, imgs, spaceshipsUser, spaceshipAntiga, left, middle, right, leave){1207 //left1208 if (parseInt(spaceshipsUser[left]) == 1 ){1209 spaceships[left][1].style.left = "280px" ;1210 spaceships[left][1].style.top = "200px" ;1211 spaceships[left][1].style.display = "block" ;1212 spaceships[left][1].style.opacity = 0.3;1213 spaceships[left][1].width = imgs["imgsMenus"]["spaceship"+1][left].naturalWidth/2 ;1214 spaceships[left][1].height = imgs["imgsMenus"]["spaceship"+1][left].naturalHeight/2;1215 }else{1216 spaceships[left][0].style.left = "280px" ;1217 spaceships[left][0].style.top = "200px" ;1218 spaceships[left][0].style.display = "block" ;1219 spaceships[left][0].style.opacity = 0.3;1220 spaceships[left][0].width = imgs["imgsMenus"]["spaceship"+0][left].naturalWidth/2 ;1221 spaceships[left][0].height = imgs["imgsMenus"]["spaceship"+0][left].naturalHeight/2;1222 }1223 //spaceship middle1224 if (parseInt(spaceshipsUser[middle]) == 1 ){1225 buttons["chooseSpaceshipMenu"][2].style.display = "block";1226 spaceships[middle][1].style.left = "510px" ;1227 spaceships[middle][1].style.top = "100px" ;1228 spaceships[middle][1].style.display = "block" ;1229 spaceships[middle][1].style.opacity = 1;1230 spaceships[middle][1].width = imgs["imgsMenus"]["spaceship"+1][middle].naturalWidth ;1231 spaceships[middle][1].height = imgs["imgsMenus"]["spaceship"+1][middle].naturalHeight;1232 }else{1233 buttons["chooseSpaceshipMenu"][2].style.display = "none";1234 spaceships[middle][0].style.left = "510px" ;1235 spaceships[middle][0].style.top = "100px" ;1236 spaceships[middle][0].style.display = "block" ;1237 spaceships[middle][0].style.opacity = 1;1238 spaceships[middle][0].width = imgs["imgsMenus"]["spaceship"+0][middle].naturalWidth ;1239 spaceships[middle][0].height = imgs["imgsMenus"]["spaceship"+0][middle].naturalHeight;1240 }1241 //right1242 if (parseInt(spaceshipsUser[right]) == 1 ){1243 spaceships[right][1].style.left = "860px" ;1244 spaceships[right][1].style.top = "200px" ;1245 spaceships[right][1].style.display = "block" ;1246 spaceships[right][1].style.opacity = 0.3;1247 spaceships[right][1].width = imgs["imgsMenus"]["spaceship"+1][right].naturalWidth/2 ;1248 spaceships[right][1].height = imgs["imgsMenus"]["spaceship"+1][right].naturalHeight/2;1249 }else{1250 spaceships[right][0].style.left = "860px" ;1251 spaceships[right][0].style.top = "200px" ;1252 spaceships[right][0].style.display = "block";1253 spaceships[right][0].style.opacity = 0.3;1254 spaceships[right][0].width = imgs["imgsMenus"]["spaceship"+0][right].naturalWidth/2 ;1255 spaceships[right][0].height = imgs["imgsMenus"]["spaceship"+0][right].naturalHeight/2;1256 }1257 //leave 1258 if(leave != "aqui leave no existe"){1259 spaceships[leave][0].style.display = "" ;1260 spaceships[leave][1].style.display = "" ;1261 //texts1262 menus["chooseSpaceshipMenu"].children["BoxAc"].children["spaceship"+spaceshipAntiga].style.display = "";1263 menus["chooseSpaceshipMenu"].children["BoxSpecs"].children["spaceship"+spaceshipAntiga].style.display = "";1264 }1265 //texts1266 menus["chooseSpaceshipMenu"].children["BoxAc"].children["spaceship"+middle].style.display = "block";1267 menus["chooseSpaceshipMenu"].children["BoxSpecs"].children["spaceship"+middle].style.display = "block";1268}1269function putCorrectSpaceships(auxMisc, menus, buttons, spaceships, imgs){1270 //var data = player.getCookie(auxMisc["playerAtual"]);1271 var spaceshipsUser = auxMisc["cookieStore"]["Spaceships"];1272 1273 let nSpaceships = (menus["chooseSpaceshipMenu"].childElementCount-6)/2 ; 1274 auxMisc["currentSpaceship"] = 0;1275 //erases everything in the beggining, then it writes.1276 for (let i = 0 ; i < nSpaceships;i++){1277 spaceships[i][0].style.display = "";1278 spaceships[i][1].style.display = "";1279 }1280 for (let i = 0 ; i < nSpaceships;i++){1281 menus["chooseSpaceshipMenu"].children["BoxAc"].children["spaceship"+i].style.display = "";1282 menus["chooseSpaceshipMenu"].children["BoxSpecs"].children["spaceship"+i].style.display = "";1283 }1284 var left = myMod(auxMisc["currentSpaceship"] - 1,nSpaceships);1285 var right = myMod(auxMisc["currentSpaceship"] + 1, nSpaceships);1286 auxChangeSpaceships(menus, buttons,spaceships,imgs, spaceshipsUser, "no ha spaceship old", left, auxMisc["currentSpaceship"], right, "aqui leave no existe");1287}1288function domSpaceships(menus){1289 var spaceships = [];1290 let nSpaceships = (menus["chooseSpaceshipMenu"].childElementCount-6)/2 ; 1291 //spaceships1292 for (let i = 0 ; i < nSpaceships;i++){1293 spaceships[i] = []1294 var spaceshipLocked = menus["chooseSpaceshipMenu"].children["spaceship0_"+i];1295 spaceships[i].push(spaceshipLocked);1296 var spaceship = menus["chooseSpaceshipMenu"].children["spaceship1_"+i];1297 spaceships[i].push(spaceship);1298 }1299 return spaceships;1300}1301function myMod(n, m) {1302 return ((n % m) + m) % m;1303}1304function togglePauseMenu(buttons, menus, auxMisc, sounds, musics, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){1305 updateSoundButton(sounds, musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);1306 buttons["pauseMenu"][6].style.display = "none";1307 // only clicks on the options if the popUpMenu is with style.display = ""1308 if(menus["pauseMenu"].style.display == "" && menus["popUpMenu"].style.display == ""){1309 menus["pauseMenu"].style.display = "block";1310 sounds["esc"][0].load();1311 sounds["esc"][0].play().catch(function(){});1312 for (var i = 0 ; i < buttons[auxMisc["currentMenu"]].length; i++){1313 buttons[auxMisc["currentMenu"]][i].removeEventListener("click",auxClickHandler);1314 buttons[auxMisc["currentMenu"]][i].removeEventListener("mouseover",auxMouseInHandler);1315 buttons[auxMisc["currentMenu"]][i].removeEventListener("mouseout",auxMouseOutHandler);1316 }1317 }//if the user is ingame and he unlocks a spaceship, only click on options when the popUpMenu disappears1318 else if (menus["popUpMenu"].style.display == ""){1319 menus["pauseMenu"].style.display = "";1320 sounds["esc"][1].load();1321 sounds["esc"][1].play().catch(function(){});1322 for (var i = 0 ; i < buttons[auxMisc["currentMenu"]].length; i++){1323 buttons[auxMisc["currentMenu"]][i].addEventListener("click", auxClickHandler);1324 buttons[auxMisc["currentMenu"]][i].addEventListener("mouseover", auxMouseInHandler);1325 buttons[auxMisc["currentMenu"]][i].addEventListener("mouseout", auxMouseOutHandler);1326 }1327 }1328}1329function removeEventListeners(buttons, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){1330 window.removeEventListener("keydown",auxKeyDownHandler); 1331 for (let key in buttons){1332 if (key != "pauseMenu"){1333 1334 for(let i = 0; i < buttons[key].length; i ++){1335 buttons[key][i].removeEventListener("click", auxClickHandler);1336 buttons[key][i].removeEventListener("mouseover", auxMouseInHandler);1337 buttons[key][i].removeEventListener("mouseout", auxMouseOutHandler);1338 }1339 1340 }1341 }1342}1343function firstMenu(menus, auxMisc, musics, body){1344 body.bgColor = "#00083b";1345 if(auxMisc["oldMenu"] == "fillerText"){1346 musics["music"][0].loop = true;1347 musics["music"][0].load();1348 musics["music"][0].play().catch(function(){});1349 }1350 menus["startMenu"].style.display = "block";1351 auxMisc["currentMenu"] = "startMenu";1352 auxMisc["oldMenu"] = "fillerText";1353}1354function mainMenu(menus, auxMisc, musics, body){1355 body.bgColor = "#00081d";1356 menus["canvasFigure"].style.display = "";1357 menus["loginRegMenu"].style.display = "";1358 menus["mainMenu"].style.display = "block";1359 if (auxMisc["currentMenu"] == "loginRegMenu"){1360 auxMisc["oldMenu"] = "loginRegMenu";1361 }1362 else{1363 auxMisc["oldMenu"] = "algumGame;_;";1364 //pauses every music1365 for(let key in musics){1366 for ( let i = 0; i < Object.keys(musics[key]).length; i++){1367 musics[key][i].pause();1368 musics[key][i].currentTime = 0;1369 }1370 }1371 //musics["music"][0].loop = true;1372 musics["music"][0].load();1373 musics["music"][0].play().catch(function(){});1374 menus["pauseMenu"].style.display = "";1375 }1376 auxMisc["currentMenu"] = "mainMenu";1377 readsCookies(menus, auxMisc);1378 1379}1380function login(name, menus, auxMisc, musics, body, buttons, domAux, player){1381 auxMisc["playerAtual"] = name;1382 //document.getElementById("playerMain").innerHTML = name;1383 domAux["playerMain"].innerHTML = name; 1384 mainMenu(menus, auxMisc, musics, body);1385 //readsCookies(menus, auxMisc);1386 unlocksLevels(buttons, player);1387}1388function unlocksLevels(buttons, player){1389 var level = player.level;1390 for(var i = 0; i < parseInt(level) + 1; i++){1391 buttons["levelMenu"][i].style.display = "block";1392 }1393 for(;i < buttons["levelMenu"].length -1 ;i++){1394 buttons["levelMenu"][i].style.display = "";1395 }1396}1397function readsCookies(menus, auxMisc){1398 // Loads the progress of all the players1399 // {"player1": [0,0,0,"1000"] , "player2": [1,123,0,"1110"]}1400 var players = parsesCookies();1401 //Save the players/records on the LeaderBoard (Henrique)1402 //{"Campain": {"player1": 45 ,"gameCampain":27 } ,"Endless":{"player1": 332388,"me": 3442} }1403 var records = createRecordsArray(players, auxMisc);1404 fillLeaderBoard(records, menus);1405 auxMisc["cookieStore"]["Tutorial"] = players[auxMisc["playerAtual"]][4];1406 auxMisc["cookieStore"]["Spaceships"] = players[auxMisc["playerAtual"]][3];1407}1408//We parse the cookies to get all the players information1409function parsesCookies() {1410 // Loads the progress of all the players1411 // {"player1": [0,0,0,"1000"] , "player2": [1,123,0,"1110"]}1412 var players = {};1413 var name;1414 var decodedCookies = decodeURIComponent(document.cookie);1415 var splitedCookies = decodedCookies.split(';');1416 for(let cookie in splitedCookies) {1417 var splitedCookie = splitedCookies[cookie].split('=');1418 while(splitedCookie[0][0] == ' '){1419 splitedCookie[0] = splitedCookie[0].substring(1);1420 }1421 if (splitedCookie[0].indexOf("Level") != -1) {1422 name = splitedCookie[0].substring(0,splitedCookie[0].indexOf("Level"));1423 if(players[name] == undefined){1424 players[name] = new Array();1425 }1426 players[name][0] = splitedCookie[1];1427 }else if (splitedCookie[0].indexOf("Campain") != -1) {1428 name = splitedCookie[0].substring(0,splitedCookie[0].indexOf("Campain"));1429 if(players[name] == undefined){1430 players[name] = new Array();1431 }1432 players[name][1] = splitedCookie[1];1433 }else if (splitedCookie[0].indexOf("Endless") != -1) {1434 name = splitedCookie[0].substring(0,splitedCookie[0].indexOf("Endless"));1435 if(players[name] == undefined){1436 players[name] = new Array();1437 }1438 players[name][2] = splitedCookie[1];1439 }1440 else if (splitedCookie[0].indexOf("Spaceships") != -1) {1441 name = splitedCookie[0].substring(0,splitedCookie[0].indexOf("Spaceships"));1442 if(players[name] == undefined){1443 players[name] = new Array();1444 }1445 players[name][3] = splitedCookie[1];1446 }1447 else if (splitedCookie[0].indexOf("Tutorial") != -1) {1448 name = splitedCookie[0].substring(0,splitedCookie[0].indexOf("Tutorial"));1449 if(players[name] == undefined){1450 players[name] = new Array();1451 }1452 players[name][4] = splitedCookie[1];1453 }1454 1455 }1456 return players;1457}1458function createRecordsArray(players, auxMisc){1459 //Save the players/records on the LeaderBoard (Henrique)1460 //{"Campain": {"player1": 45 ,"gameCampain":27 } ,"Endless":{"player1": 332388,"me": 3442} }1461 var records = {"Campain":{}, "Endless":{} };1462 for (let user in players){1463 //verificar se ja tem os levels every desbloqueados1464 if (players[user][0] == auxMisc["maxLevel"] && players[user][1] != 0){1465 //coloca o player no dict dos records1466 records["Campain"][user] = players[user][1];1467 }1468 if (players[user][2] != 0){1469 //coloca o player no dict dos records1470 records["Endless"][user] = players[user][2];1471 }1472 }1473 // Sort Campain1474 // Create items array1475 var items = Object.keys(records["Campain"]).map(function(key) {1476 return [key, records["Campain"][key]];1477 });1478 // Sort the array based on the second element1479 items.sort(function(first, second) {1480 return second[1] - first[1];1481 });1482 var aux = {"Campain":{} };1483 for (let i = 0;i < items.length;i++){1484 aux["Campain"][items[i][0]] = items[i][1];1485 }1486 records["Campain"] = aux["Campain"];1487 // Sort Endless1488 // Create items array1489 var items = Object.keys(records["Endless"]).map(function(key) {1490 return [key, records["Endless"][key]];1491 });1492 // Sort the array based on the second element1493 items.sort(function(first, second) {1494 return second[1] - first[1];1495 });1496 var aux = {"Endless":{} };1497 for (let i = 0;i < items.length;i++){1498 aux["Endless"][items[i][0]] = items[i][1];1499 }1500 records["Endless"] = aux["Endless"];1501 return records;1502}1503function fillLeaderBoard(records, menus){1504 var list = menus["leaderBoard"].children["LeaderBoardTable"].children["listC"];1505 var player = list.children["playerC"];1506 var result = list.children["score"];1507 //declared as var i, so it stays with the value of when the for ended1508 var i;1509 //CAMPAIN1510 for (i = 0; i < 6 && i < Object.keys(records["Campain"]).length; i++){1511 player.children[i].innerHTML = Object.keys(records["Campain"])[i];1512 result.children[i].innerHTML = Object.values(records["Campain"])[i];1513 }1514 for (;i < 6; i++){1515 player.children[i].innerHTML = "";1516 result.children[i].innerHTML = "";1517 }1518 var list = menus["leaderBoard"].children["LeaderBoardTable"].children["listI"];1519 var player = list.children["playerI"];1520 var result = list.children["time"];1521 //ENDLESS1522 for (i = 0; i < 6 && i < Object.keys(records["Endless"]).length; i++){1523 player.children[i].innerHTML = Object.keys(records["Endless"])[i];1524 result.children[i].innerHTML = Object.values(records["Endless"])[i];1525 }1526 for (;i < 6; i++){1527 player.children[i].innerHTML = "";1528 result.children[i].innerHTML = "";1529 }1530}1531//return true/false if the player does/doesn't exist.1532function checkCookie(name) {1533 var counter = 0;1534 var decodedCookies = decodeURIComponent(document.cookie);1535 var splitedCookies = decodedCookies.split(';');1536 for(let cookie in splitedCookies) {1537 var splitedCookie = splitedCookies[cookie].split('=');1538 while(splitedCookie[0][0] == ' '){1539 splitedCookie[0] = splitedCookie[0].substring(1);1540 }1541 if(splitedCookie[0].indexOf(name) == 0 &&1542 (splitedCookie[0].substring(name.length) == "Level" ||1543 splitedCookie[0].substring(name.length) == "Campain" ||1544 splitedCookie[0].substring(name.length) == "Endless" ||1545 splitedCookie[0].substring(name.length) == "Spaceships" ||1546 splitedCookie[0].substring(name.length) == "Tutorial") ) {1547 counter++;1548 if(counter == 5){1549 return true;1550 }1551 }1552 }1553 return false;1554}1555function deleteCookie(name) {1556 document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/";...

Full Screen

Full Screen

jquery.mockjax.js

Source:jquery.mockjax.js Github

copy

Full Screen

...87 function getMockForRequest( handler, requestSettings ) {88 // If the mock was registered with a function, let the function decide if we89 // want to mock this request90 if ( $.isFunction(handler) ) {91 return handler( requestSettings );92 }93 // Inspect the URL of the request and check if the mock handler's url94 // matches the url for this ajax request95 if ( $.isFunction(handler.url.test) ) {96 // The user provided a regex for the url, test it97 if ( !handler.url.test( requestSettings.url ) ) {98 return null;99 }100 } else {101 // Look for a simple wildcard '*' or a direct URL match102 var star = handler.url.indexOf('*');103 if (handler.url !== requestSettings.url && star === -1 ||104 !new RegExp(handler.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&").replace(/\*/g, '.+')).test(requestSettings.url)) {105 return null;...

Full Screen

Full Screen

core.js

Source:core.js Github

copy

Full Screen

...19 }20 return e;21 }22};23function test_handler( test_name, res, exp ) {24 var is_err = ($.isFunction(exp) && exp.prototype instanceof Error);25 if ( is_err && res instanceof exp ) {26 ok( res instanceof exp, test_name );27 }28 else {29 same( res, exp, test_name );30 }31}32// these are used throughout to test if tag blocks suppress them33jQuery.tmpl.tag.syntax_error = { open: "throw SyntaxError('test syntax error');" };34jQuery.tmpl.tag.reference_error = { open: "throw ReferenceError('test reference error');" };35jQuery.tmpl.tag.type_error = { open: "throw TypeError('test type error');" };36module("Basics");37 test("Basic Function", function() {38 test_handler( 'plain text passes through untouched', R('lorem ipsum', testData), 'lorem ipsum' );39 // TODO fixme40 //test_handler( 'whitespace is left untouched', R('\n\tlorem\n\n\tipsum \t', testData), '\n\tlorem\n\n\tipsum \t' );41 test_handler( 'simple variable output', R("${ one }", testData), "first" );42 // throw errors with incomplete syntax43 test_handler( 'multi word variable tag', R("${ a b c }}"), SyntaxError );44 test_handler( "_ (underscore) cannot by used by data", R('${ _ }', {'_':'foo'}), TypeError );45 test_handler( "$ cannot be used by data", R('${ $ }', {'$':'foo'}), TypeError );46 });47 // test errors are passed back correctly48 test("Error Passing", function(){49 test_handler( 'syntax', R("{{syntax_error }}", testData), SyntaxError );50 test_handler( 'reference', R("{{reference_error }}", testData), ReferenceError );51 test_handler( 'type', R("{{type_error }}", testData), TypeError );52 });53 // newlines should work because: ${ foo + "\n" } and they have whitespace management benefits54 test("Newlines / Escaping", function(){55 test_handler( "newlines do not kill tags", R('${\n \none\n }', testData), 'first');56 // TODO fixme57 //test_handler( "newlines in strings don't kill tags", R('${ "on\ne" }', testData), 'on\ne' );58 //test_handler( "returns do not kill tags", R('${\r \r\none\r\n }', testData), 'first');59 //test_handler( "returns in strings don't kill tags", R('${ "on\re" }', testData), 'on\re' );60 //test_handler( "slashes in strings don't kill tags", R('${ "on\\e" }', testData), 'on\\e');61 //test_handler( "newlines don't kill parsing", R('a\nb\nc${ 8 }.'), 'a\nb\nc8.');62 });63 test("Empty Tag", function() {64 // TODO fixme65 //test_handler( 'default', R("{{}}", testData), '{{}}' );66 //test_handler( 'with whitespace', R("{{ }}"), '{{ }}' );67 //test_handler( 'with tabs whitespace', R("{{\t\t}}"), '{{\t\t}}' );68 });69 test("Incorrect Nesting", function() {70 test_handler( 'default', R("{{if 1}}{{if 1}}{{/if}}", testData), SyntaxError );71 test_handler( 'extra /if', R("{{if 1}}{{/if}}{{/if}}", testData), SyntaxError );72 test_handler( 'but terminated', R("{{if 1}}{{each arr}}{{/if}}{{/each}}", testData), SyntaxError );73 });74 test("Ignore Malformed Tags", function() {75 test_handler( 'a {{one } b', R("a {{one } b", testData), 'a {{one } b' );76 test_handler( 'first} {{second }', R("${ one }} {{two }", testData), 'first} {{two }' );77 test_handler( '{{one }', R('{{one }', testData), '{{one }' );78 });79 // reserved words80 test("Reserved Words", function(){81 // TODO fixme82 //test_handler( "Disallow new operator", R('${ new Object() }',{}), SyntaxError );83 //test_handler( "Disallow delete operator", R('${ delete a }',{a:1}), SyntaxError );84 test_handler( "Disallow function operator", R('${ function(){} }',{}), SyntaxError );85 test_handler( "Disallow return", R('${ return a }',{a:1}), SyntaxError );86 test_handler( "Disallow for", R('${ for a }',{a:1}), SyntaxError );87 test_handler( "Disallow do/while", R('${ do{ a }while(a) }',{a:1}), SyntaxError );88 test_handler( "Disallow if", R('${ if a }',{a:1}), SyntaxError );89 test_handler( "Disallow try/catch", R('${ try{b.s}catch(e){} }',{a:1}), SyntaxError );90 test_handler( "Disallow return keyword", R('${ return a }',{a:1}), SyntaxError );91 test_handler( "Disallow with keyword", R('${ with (s) }',{a:1}), SyntaxError );92 test_handler( "Disallow throw keyword", R('${ throw "foo" }',{a:1}), SyntaxError );93 });94 // these tests are a bit awkward because caching is done in $.render, not $.tmpl95 test("Caching via $.template() and .template()", function() {96 $.template('nametmpl', '<span>name: ${ v }</span>' );97 test_handler( "using a named template", $.tmpl('nametmpl', testData).text(), 'name: test' );98 var $elm = $( "<span>name: ${ v }</span>" );99 $elm.template('nametmpl2');100 test_handler( "using a named template created from a node", $.tmpl('nametmpl2', testData).text(), 'name: test' );101 });102 test("Bracketed Accessors", function(){103 test_handler( "foo[\"bar\"]", R('${ foo["bar"] }',{foo:{bar:'baz'}}), 'baz' );104 test_handler( "foo['bar']", R("${ foo['bar'] }",{foo:{bar:'baz'}}), 'baz' );105 });106 test("Escaping", function(){107 // TODO fixme108 //test_handler( 'echoing escapes html', R("${ 'foo<div>bar</div>baz' }"), 'foo&lt;div&gt;bar&lt;/div&gt;baz' );109 //test_handler( 'echoing escapes html (lookup)', R("${ r }", {r:'foo<div>bar</div>baz'}), 'foo&lt;div&gt;bar&lt;/div&gt;baz' );110 //test_handler( 'echoing escapes ampersands 1', R("${ '&' }"), '&amp;' );111 //test_handler( 'echoing escapes ampersands 2', R("${ '&amp;' }"), '&amp;amp;' );112 //test_handler( 'echoing escapes & < >', R("${ '-<&>-<&>-' }"), '-&lt;&amp;&gt;-&lt;&amp;&gt;-' );113 });114 test("Comments", function() {115 test_handler( "comments are removed", R('A{{! comments test }}B', testData), "AB" );116 test_handler( "comments are removed (2)", R('{{! inky }}foo{{! blinky }}', testData), 'foo' );117 // TODO fixme118 return;119 test_handler( "comments may include string of comments", R('A{{! comments "}}" test }}B', testData), "AB" );120 test_handler( "comments cannot nest other comments", R('A{# C{# E #}D #}B', testData), "AD #}B" );121 test_handler( "comments may include strings with escapes (double)", R('A{# comments "str\"ing" test #}B', testData), "AB" );122 test_handler( "comments may include strings with escapes (single)", R("A{# comments 'str\'ing' test #}B", testData), "AB" );123 test_handler( "comments may include tags", R("A{# {{= v }} #}B", testData), "AB" );124 test_handler( "comments may span lines", R("A{# \ncomments test\n #}B", testData), "AB" );125 test_handler( "comments may contain invalid content (invalid tag)", R('1{{! {{ INVALID_TAG }} }}2', testData), '12' );126 test_handler( "comments may contain invalid content (stray end tag)", R('1{{! {{/if}} }}2', testData), '12' );127 test_handler( "comments may contain invalid content (stray else)", R('1{{! {{else}} }}2', testData), '12' );128 test_handler( "comments may contain invalid content (invalid javascript)", R('1{{! {{if ...}} }}2', testData), '12' );129 });130 test("Variables", function() {131 test_handler( "variable replacement", R('${ one }', testData), "first" );132 test_handler( "many variables work", R('${ one }/${ two }', testData), "first/second" );133 test_handler( "alternative variable syntax", R('${ one }', testData), "first" );134 test_handler( "many variables work with alt syntax", R('${ one }/${ two }', testData), "first/second" );135 test_handler( "basic string output (double)", R('${ "string" }', testData), "string" );136 test_handler( "basic string output (single)", R("${ 'string' }", testData), "string" );137 test_handler( "string quote escapes (double)", R('${ "str\\"i\\"ng" }', testData), 'str"i"ng' );138 test_handler( "string quote escapes (single)", R("${ 'str\\'i\\'ng' }", testData), "str'i'ng" );139 // TODO fixme140 //test_handler( "string output with tag", R('${ "\\{\\{ tag \\}\\}" }', testData), "{{ tag }}" );141 //test_handler( "string output with end of tag", R('${ "\\}\\}" }', testData), "}}" );142 test_handler( 'empty variable tag (with tabs whitespace)', R("{{=\t\t}}", "self"), 'self' );143 test_handler( 'empty variable tag', R("{{= }}", "self"), 'self' );144 test_handler( 'empty variable tag (with space)', R("{{=}}", "self"), 'self' );145 test_handler( "variable lookup error suppression", R('${ is_undefined }', testData), '' );146 // TODO fixme147 //test_handler( "variable lookup error suppression (with member)", R('${ is_undefined.member }', testData), '' );148 test_handler( "variable and text (1)", R('A${ one }', testData), 'Afirst' );149 test_handler( "variable and text (2)", R('${ one }B', testData), 'firstB' );150 test_handler( "variable and text (3)", R('A${ one }B', testData), 'AfirstB' );151 test_handler( "lookups work for submembers", R('${ a.b.c }', {a:{b:{c:"abc"}}}), 'abc' );152 test_handler( "error suppression works for submembers", R('${ a.b.c }', {a:{b:{c:"abc"}}}), 'abc' );153 test_handler( "functions can be called with in tags", R('${ foo() }', { foo:function(s){ return "bar"; }}), 'bar' );154 test_handler( "functions pass strings correctly", R('${ foo("bar") }', { foo:function(s){ return s; }}), 'bar' );155 test_handler( "functions pass arguments correctly", R('${ foo(bar) }', { foo:function(s){ return s; }, 'bar':'baz'}), 'baz' );156 var cls = {157 toString:function () {return 'S';},158 toValue:function () {return 'V';}159 }160 test_handler( 'variables use toString, not toValue', R("${ foo }",{foo:cls}), 'S' );161 test_handler( 'comma passes variables correctly', R("${ dot,dot,comma,dash }",{dot:'.','comma':',','dash':'-'}), '-' );162 // TODO fixme163 // @borgar says: I don't like this: it should use foo() to be consistant with foo().bar()164 test_handler( 'variable gets called if it is callable', R("${ fun }", testData), 'RETURNED' );165 test_handler( 'last variable in sequence gets called if it is callable', R("${ obj.fun }",{obj: testData}), 'RETURNED' );166 var cls = {167 foo: function () {168 return { bar: function () {return 'BAZ'; } };169 }170 }171 test_handler( 'member functions in a sequence don\'t get called', R("${ foo.bar }", cls), '' );172 });173 test("Falsy Values", function(){174 test_handler( "(0)", R('${ 0 }'), '0' );175 test_handler( "(false)", R('${ false }'), 'false' );176 test_handler( "(null)", R('${ zero }'), '' ); // it's debatable what we want here177 test_handler( "(undefined)", R('${ undefined }'), '' );178 test_handler( "(\"\")", R('${ "" }'), '' );179 test_handler( "('')", R("${ '' }"), '' );180 });181 test("Falsy Lookups", function(){182 test_handler( "(false)", R('${ zero }', {zero: 0}), '0' );183 test_handler( "(false)", R('${ zero }', {zero: false}), 'false' );184 test_handler( "(null)", R('${ zero }', {zero: null}), '' ); // it's debatable what we want here185 test_handler( "(undefined)", R('${ zero }', {zero: undefined}), '' );186 test_handler( "('')", R('${ zero }', {zero: ""}), '' );187 });188 test("Javascript Operations", function(){189 test_handler( "string concatination", R('${ one + "foo" }', testData), "firstfoo" );190 test_handler( "adding", R('${ 1 + 5 }', testData), "6" );191 test_handler( "subtracting", R('${ 9 - 5 }', testData), "4" );192 test_handler( "modulo", R('${ 5 % 2 }', testData), "1" );193 test_handler( "unary minus", R('${ -n }',{n:10}), "-10" );194 test_handler( "unary plus", R('${ +n }',{n:"10"}), "10" );195 test_handler( "in operator", R('${ "bar" in foo }',{foo:{bar:'baz'}}), "true" );196 test_handler( "instanceof operator", R('${ foo instanceof Date }',{foo:new Date()}), "true" );197 test_handler( "typeof operator", R('${ typeof "str" }',{}), "string" );198 test_handler( "bitwise AND", R('${ n & 1 }',{n:5}), "1" );199 test_handler( "bitwise OR", R('${ n | 1 }',{n:4}), "5" );200 test_handler( "bitwise XOR", R('${ n ^ 1 }',{n:5}), "4" );201 test_handler( "bitwise NOT", R('${ ~n }',{n:5}), "-6" );202 test_handler( "left shift", R('${ n << 1 }',{n:5}), "10" );203 test_handler( "right shift", R('${ n >> 1 }',{n:5}), "2" );204 test_handler( "zero-fill right shift", R('${ n >>> 1 }',{n:5}), "2" );205 test_handler( "comparing ==", R('${ 1 == 5 }', testData), "false" );206 test_handler( "comparing !=", R('${ 1 != 5 }', testData), "true" );207 test_handler( "comparing ===", R('${ 5 === 5 }', testData), "true" );208 test_handler( "comparing !==", R('${ 5 !== 5 }', testData), "false" );209 test_handler( "comparing >=", R('${ 1 >= 5 }', testData), "false" );210 test_handler( "comparing >", R('${ 1 > 5 }', testData), "false" );211 test_handler( "comparing <=", R('${ 1 <= 5 }', testData), "true" );212 test_handler( "comparing <", R('${ 1 < 5 }', testData), "true" );213 test_handler( "Logical OR", R('${ zero || "FALSY" }',{ zero: 0 }), "FALSY" );214 test_handler( "Logical AND", R('${ zero && "TRUEY" }',{ zero: 1 }), "TRUEY" );215 test_handler( "Conditional Operator", R('${ zero ? "zero" : "other" }',{ zero: 1 }), "zero" );216 test_handler( "Unary logical NOT", R('${ !zero }',{ zero: 1 }), "false" );217 test_handler( "Single-Quoted Strings", R("${ 'test' }",{}), "test" );218 test_handler( "Single-Quoted Comparison", R("${ 'test' == testvar }",{ testvar: 'test' }), "true" );219 });220 test("Disallowed / Illegal", function(){221 // TODO fixme222 /*223 test_handler( "Disallow incremental assignment", R('${ a += 1 }', {a:1}), SyntaxError );224 test_handler( "Disallow decremental assignment", R('${ a -= 1 }', {a:1}), SyntaxError );225 test_handler( "Disallow multiply assignment", R('${ a *= 1 }', {a:1}), SyntaxError );226 test_handler( "Disallow division assignment", R('${ a /= 1 }', {a:1}), SyntaxError );227 test_handler( "Disallow left shift assignment", R('${ a <<= 1 }', {a:1}), SyntaxError );228 test_handler( "Disallow right shift assignment", R('${ a >>= 1 }', {a:1}), SyntaxError );229 test_handler( "Disallow zero-fill right shift assignment", R('${ a >>>= 1 }', {a:1}), SyntaxError );230 test_handler( "Disallow bitwise AND assignment", R('${ a &= 1 }', {a:1}), SyntaxError );231 test_handler( "Disallow bitwise OR assignment", R('${ a |= 1 }', {a:1}), SyntaxError );232 test_handler( "Disallow bitwise XOR assignment", R('${ a ^= 1 }', {a:1}), SyntaxError );233 test_handler( "Disallow literal object creation", R('${ { a:"a"} }', {a:1}), SyntaxError );234 test_handler( "Disallow literal array creation", R('${ [1,2,3] }', {a:1}), SyntaxError );235 test_handler( "Disallow decrement", R('${ --a }',{a:1}), SyntaxError );236 test_handler( "Disallow assignments", R('${ (a = 2) }',{a:1}), SyntaxError );237 */238 });239module("Commands");240 test("Create New Command", function(){241 $.getText = function ( str ) { return str.toUpperCase(); };242 $.tmpl.tag.trans = { open: "_.push($.getText($1));" };243 test_handler( "creating new command works", R('{{trans "translate" }}'), 'TRANSLATE' );244 $.tmpl.tag._ = $.tmpl.tag.trans;245 test_handler( "_ can by assigned a command", R('{{_ "translate" }}', {}), 'TRANSLATE' );246 delete $.getText;247 delete $.tmpl.tag.trans;248 delete $.tmpl.tag._;249 });250 test("Each {{ each }}", function() {251 test_handler( "loop", R('{{each arr}}${ $index }:${ this }/{{/each}}', testData), '0:AA/1:BB/2:CC/' );252 test_handler( "loop", R('{{each arr}}${ $index }:${ $value }/{{/each}}', testData), '0:AA/1:BB/2:CC/' );253 test_handler( "loop", R('{{each(i, item) arr}}${ i }:${ item }/{{/each }}', testData), '0:AA/1:BB/2:CC/' );254 test_handler( "loop", R('{{each arr}}${ $index }:${ this }/{{/each }}', testData), '0:AA/1:BB/2:CC/' );255 // TODO fixme256 //test_handler( "first", R('{{each dict}}${ $index }:{{if $first }}first{{else}}!first{{/if }}/{{/each }}', testData), 'leovinus:first/scraliontis:!first/brobostigon:!first/' );257 //test_handler( "first", R('{{each dict}}{{if !$first }}, {{/if }}${ $index }:${ this }}{{/each }}', testData), 'leovinus:this, scraliontis:that, brobostigon:other' );258 // TODO fixme259 //test_handler("html content", R('{{each arr}}<a>${ $index }</a>{{/each}}', testData), '<a>0</a><a>1</a><a>2</a>' );260 //test_handler("html content", R('{{each arr}}<a>${ this }</a>{{/each}}', testData), '<a>AA</a><a>BB</a><a>CC</a>' );261 //test_handler("html content", R('{{each this}}<a>${ data }</a>{{/each}}', [{data: 0}, {data: 1}, {data: 2}]), '<a>0</a><a>1</a><a>2</a>' );262 //test_handler("html content with newlines", R('{{each this}}\n<a>${ data }</a>\n{{/each}}', [{data: 0}, {data: 1}, {data: 2}]), '\n<a>0</a>\n\n<a>1</a>\n\n<a>2</a>\n' );263 test_handler( 'errors are passed back correctly (syntax)', R("{{each arr}}${ $i }{{syntax_error}}{{/each}}", testData), SyntaxError );264 test_handler( 'errors are passed back correctly (reference)', R("{{each arr}}${ $i }{{reference_error}}{{/each}}", testData), ReferenceError );265 test_handler( 'errors are passed back correctly (type)', R("{{each arr}}${ $i }{{type_error}}{{/each}}", testData), TypeError );266 });267 test("{{if}} and {{else}}", function() {268 test_handler( "if:true", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:true }), 'TRUE' );269 test_handler( "if:false", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:false }), 'FALSE' );270 test_handler( "if:null", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:null }), 'FALSE' );271 test_handler( "if:undefined", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:undefined }), 'FALSE' );272 test_handler( "if:[]", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:{} }), 'TRUE' );273 test_handler( "if:{}", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:[] }), 'TRUE' );274 test_handler( "if:''", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:"" }), 'FALSE' );275 test_handler( "if:A", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:"A" }), 'TRUE' );276 test_handler( "if:0", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:0 }), 'FALSE' );277 test_handler( "if:1", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:1 }), 'TRUE' );278 test_handler( "/if ignores following text", R('{{if a}}TRUE{{else}}FALSE{{/if a}}', { a:1 }), 'TRUE' );279 test_handler( 'errors are passed back correctly (syntax)', R("{{if true}}{{syntax_error}}{{/if}}", testData), SyntaxError );280 test_handler( 'errors are passed back correctly (reference)', R("{{if true}}{{reference_error}}{{/if}}", testData), ReferenceError );281 test_handler( 'errors are passed back correctly (type)', R("{{if true}}{{type_error}}{{/if}}", testData), TypeError );282 });283 test("{{tmpl() template}}", function() {284 jQuery.template('test', '${ "test text" }');285 test_handler( "simple include", R('{{tmpl "test"}}'), 'test text' );286 jQuery.template('test2', '{{each arr}}[${ $value }]-{{/each }}');287 test_handler( "data access", R('{{tmpl "test2"}}', testData), '[AA]-[BB]-[CC]-' );288 var nestedData = {foo: 'bar'};289 jQuery.template('nested', '{{tmpl "nested0"}}');290 jQuery.template('nested0', '${ foo }');291 test_handler( "nested - 1 level", R('{{tmpl "nested"}}', nestedData), 'bar' );292 jQuery.template('nested0', '{{tmpl "nested1"}}');293 jQuery.template('nested1', '{{tmpl "nested2"}}');294 jQuery.template('nested2', '${ foo }');295 test_handler( "nested - 2 levels", R('{{tmpl "nested" }}', nestedData), 'bar' );296 nestedData = {foo: {bar: {sweet: 1} } };297 jQuery.template('nested2', '${ foo.bar.sweet }');298 test_handler( "nested - 2 levels - complex data", R('{{tmpl "nested" }}', nestedData), '1' );299 // TODO fixme300 jQuery.template('test', '${ $index }');301 //test_handler( "{{each}} index variable", R('{{each arr}}{{tmpl "test" }}{{/each}}', testData), '012' );302 jQuery.template('test', '${ n }');303 //test_handler( "{{each}} index variable", R('{{each(n, item) arr}}{{tmpl "test"}}{{/each}}', testData), '012' );304 jQuery.template('test', '${ item }');305 //test_handler( "{{each}} item variable", R('{{each(n, item) arr}}{{tmpl "test" }}{{/each}}', testData), 'AABBCC' );306 });307 test("Html Output Unecoded {{html }}", function(){308 // TODO fixme309 //test_handler("encoded", R('{{= html}}', testData), '&lt;a&gt;');310 //test_handler("unencoded", R('{{html html}}', testData), '<a>');311 });312module("Script Tag Caching");313 test("Template Reuse", function(){314 var template = $('#reuse'),315 data = {data: 'pass1'};316 var pass1 = template.tmpl(data).html();317 data = {data: 'pass2'};318 var pass2 = template.tmpl(data).html();319 ok( "simple reuse test", pass1 == 'pass1' && pass2 == 'pass2' );...

Full Screen

Full Screen

quantiModo.js

Source:quantiModo.js Github

copy

Full Screen

1angular.module('starter') 2 // QuantiModo API implementation3 .factory('QuantiModo', function($http, $q, authService){4 var QuantiModo = {};5 // Handler when request is failed6 var onRequestFailed = function(error){7 console.log("Not Allowed! error : "+ error);8 };9 // GET method with the added token10 QuantiModo.get = function(baseURL, allowedParams, params, successHandler, errorHandler){11 authService.getAccessToken().then(function(token){12 13 // configure params14 var urlParams = [];15 for (var key in params) 16 {17 if (jQuery.inArray(key, allowedParams) == -1) 18 { 19 throw 'invalid parameter; allowed parameters: ' + allowedParams.toString(); 20 }21 urlParams.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key]));22 }23 // configure request24 var url = config.getURL(baseURL);25 var request = { 26 method : 'GET', 27 url: (url + ((urlParams.length == 0) ? '' : urlParams.join('&'))), 28 responseType: 'json', 29 headers : {30 "Authorization" : "Bearer " + token.accessToken,31 'Content-Type': "application/json"32 }33 };34 $http(request).success(successHandler).error(function(data,status,headers,config){35 var error = "Error";36 if (data && data.error && data.error.message) error = data.error.message; 37 Bugsnag.notify("API Request to "+request.url+" Failed",error,{},"error");38 errorHandler(data,status,headers,config);39 });40 }, onRequestFailed);41 };42 // POST method with the added token43 QuantiModo.post = function(baseURL, requiredFields, items, successHandler, errorHandler){44 authService.getAccessToken().then(function(token){45 46 console.log("TOKKEN : ", token.accessToken);47 // configure params48 for (var i = 0; i < items.length; i++) 49 {50 var item = items[i];51 for (var j = 0; j < requiredFields.length; j++) { 52 if (!(requiredFields[j] in item)) { 53 throw 'missing required field in POST data; required fields: ' + requiredFields.toString(); 54 } 55 }56 }57 // configure request58 var request = { 59 method : 'POST', 60 url: config.getURL(baseURL),61 responseType: 'json', 62 headers : {63 "Authorization" : "Bearer " + token.accessToken,64 'Content-Type': "application/json"65 },66 data : JSON.stringify(items)67 };68 $http(request).success(successHandler).error(function(data,status,headers,config){69 var error = "Error";70 if (data && data.error && data.error.message) error = data.error.message; 71 Bugsnag.notify("API Request to "+request.url+" Failed",error,{},"error");72 errorHandler(data,status,headers,config);73 });74 }, errorHandler);75 };76 // get Measuremnets for user77 var getMeasurements = function(params, successHandler, errorHandler){78 QuantiModo.get('api/measurements',79 ['variableName', 'startTime', 'endTime', 'groupingWidth', 'groupingTimezone', 'source', 'unit','limit','offset','lastUpdated'],80 params,81 successHandler,82 errorHandler);83 };84 QuantiModo.getMeasurements = function(params){85 var defer = $q.defer();86 var response_array = [];87 var errorCallback = function(){88 defer.resolve(response_array);89 };90 var successCallback = function(response){91 if(response.length === 0 || typeof response === "string"){92 defer.resolve(response_array);93 }else{94 response_array = response_array.concat(response);95 params.offset+=200;96 defer.notify(response);97 getMeasurements(params,successCallback,errorCallback);98 }99 }100 getMeasurements(params,successCallback,errorCallback);101 return defer.promise;102 }103 // post measurements old method104 QuantiModo.postMeasurements= function(measurements, successHandler ,errorHandler) { 105 QuantiModo.post('api/measurements',106 ['source', 'variable', 'combinationOperation', 'timestamp', 'value', 'unit'],107 measurements,108 successHandler,109 errorHandler);110 };111 // post new Measurements for user112 QuantiModo.postMeasurementsV2 = function(measurementset, successHandler ,errorHandler){113 QuantiModo.post('api/measurements/v2', 114 ['measurements', 'name', 'source', 'category', 'combinationOperation', 'unit'], 115 measurementset, 116 successHandler,117 errorHandler);118 };119 // get positive list120 QuantiModo.getCauses = function(successHandler, errorHandler){121 var tracking_factor = config.appSettings.primary_tracking_factor_details.name.replace(' ','%20');122 QuantiModo.get('api/v1/variables/'+tracking_factor+'/public/causes',123 [],124 {},125 successHandler,126 errorHandler);127 };128 //get User's causes129 QuantiModo.getUsersCauses = function (successHandler,errorHandler) {130 var tracking_factor = config.appSettings.primary_tracking_factor_details.name.replace(' ','%20');131 QuantiModo.get('api/v1/variables/'+tracking_factor+'/causes',132 [],133 {},134 successHandler,135 errorHandler136 );137 };138 // get negative list139 QuantiModo.getNegativeList = function(successHandler, errorHandler){140 var tracking_factor = config.appSettings.primary_tracking_factor_details.name.replace(' ','%20');141 QuantiModo.get('api/v1/variables/'+tracking_factor+'/public/effects',142 [],143 {},144 successHandler,145 errorHandler);146 };147 // post new correlation for user148 QuantiModo.postCorrelation = function(correlationSet, successHandler ,errorHandler){149 QuantiModo.post('api/v1/correlations', 150 ['cause', 'effect', 'correlation', 'vote'], 151 correlationSet, 152 successHandler,153 errorHandler);154 };155 // post a vote156 QuantiModo.postVote = function(correlationSet, successHandler ,errorHandler){157 QuantiModo.post('api/v1/votes',158 ['cause', 'effect', 'correlation', 'vote'],159 correlationSet,160 successHandler,161 errorHandler);162 };163 // get public variables164 QuantiModo.getPublicVariables = function(query, successHandler, errorHandler){165 QuantiModo.get('api/v1/variables/search/'+query,166 ['limit','includePublic'],167 {'limit' : 5, 'includePublic' : true},168 successHandler,169 errorHandler);170 };171 // get public variables172 QuantiModo.getPublicVariablesByCategory = function(query,cateogry, successHandler, errorHandler){173 QuantiModo.get('api/v1/variables/search/'+query,174 ['limit','categoryName','includePublic'],175 {'limit' : 5, 'categoryName': cateogry, 'includePublic': true},176 successHandler,177 errorHandler);178 };179 // get user variables180 QuantiModo.getVariables = function(successHandler, errorHandler){181 QuantiModo.get('api/v1/variables',182 ['limit'],183 { limit:5 },184 successHandler,185 errorHandler);186 };187 // get user variables188 QuantiModo.getVariablesByCategory = function(category,successHandler, errorHandler){189 QuantiModo.get('api/v1/variables',190 ['category', 'limit'],191 {category:category, limit:5},192 successHandler,193 errorHandler);194 };195 // get variable categories196 QuantiModo.getVariableCategories = function(successHandler, errorHandler){197 QuantiModo.get('api/variableCategories',198 [],199 {},200 successHandler,201 errorHandler);202 };203 // get units204 QuantiModo.getUnits = function(successHandler, errorHandler){205 QuantiModo.get('api/units',206 [],207 {},208 successHandler,209 errorHandler);210 };211 // get user data212 QuantiModo.getUser = function(successHandler, errorHandler){213 QuantiModo.get('/api/user/me',214 [],215 {},216 successHandler,217 errorHandler);218 };219 // get reminders220 QuantiModo.getTrackingReminders = function(successHandler, errorHandler){221 QuantiModo.get('/api/v1/trackingReminders',222 [],223 {},224 successHandler,225 errorHandler);226 };227 // get pending reminders 228 QuantiModo.getTrackingReminderNotifications = function(successHandler, errorHandler){229 QuantiModo.get('/api/v1/trackingReminderNotifications',230 [],231 {},232 successHandler,233 errorHandler);234 };235 // post tracking reminder236 QuantiModo.postTrackingReminder = function(reminder, successHandler, errorHandler) { 237 console.log(reminder);238 QuantiModo.post('api/v1/trackingReminders',239 [240 'variableId', 241 'defaultValue',242 'reminderFrequency',243 'variableName',244 'variableCategoryName',245 'abbreviatedUnitName',246 'combinationOperation'247 ],248 reminder,249 successHandler,250 errorHandler);251 };252 // delete tracking reminder253 QuantiModo.deleteTrackingReminder = function(reminder, successHandler, errorHandler){254 QuantiModo.post('/api/v1/trackingReminders/delete',255 ['id'],256 {id: reminder},257 successHandler,258 errorHandler);259 };260 // snooze tracking reminder261 QuantiModo.snoozeTrackingReminder = function(reminder, successHandler, errorHandler){262 QuantiModo.post('/api/v1/trackingReminderNotifications/snooze',263 ['id'],264 {id: reminder},265 successHandler,266 errorHandler);267 };268 // skip tracking reminder269 QuantiModo.skipTrackingReminder = function(reminder, successHandler, errorHandler){270 QuantiModo.post('/api/v1/trackingReminderNotifications/skip',271 ['id'],272 {id: reminder},273 successHandler,274 errorHandler);275 };276 // track tracking reminder with default value277 QuantiModo.trackTrackingReminder = function(reminder, successHandler, errorHandler){278 QuantiModo.post('/api/v1/trackingReminderNotifications/track',279 ['id'],280 {id: reminder},281 successHandler,282 errorHandler);283 };284 return QuantiModo;...

Full Screen

Full Screen

event-handler.js

Source:event-handler.js Github

copy

Full Screen

...82 eventRegistry[uid] = eventRegistry[uid] || {};83 return eventRegistry[uid];84}85function bootstrapHandler(element, fn) {86 return function handler(event) {87 event.delegateTarget = element;88 if (handler.oneOff) {89 EventHandler.off(element, event.type, fn);90 }91 return fn.apply(element, [event]);92 };93}94function bootstrapDelegationHandler(element, selector, fn) {95 return function handler(event) {96 const domElements = element.querySelectorAll(selector);97 for (let { target } = event; target && target !== this; target = target.parentNode) {98 for (let i = domElements.length; i--; '') {99 if (domElements[i] === target) {100 event.delegateTarget = target;101 if (handler.oneOff) {102 EventHandler.off(element, event.type, fn);103 }104 return fn.apply(target, [event]);105 }106 }107 }108 // To please ESLint109 return null;...

Full Screen

Full Screen

event-handler.spec.js

Source:event-handler.spec.js Github

copy

Full Screen

1import EventHandler from '../../../src/dom/event-handler'2/** Test helpers */3import { getFixture, clearFixture } from '../../helpers/fixture'4describe('EventHandler', () => {5 let fixtureEl6 beforeAll(() => {7 fixtureEl = getFixture()8 })9 afterEach(() => {10 clearFixture()11 })12 describe('on', () => {13 it('should not add event listener if the event is not a string', () => {14 fixtureEl.innerHTML = '<div></div>'15 const div = fixtureEl.querySelector('div')16 EventHandler.on(div, null, () => {})17 EventHandler.on(null, 'click', () => {})18 expect().nothing()19 })20 it('should add event listener', done => {21 fixtureEl.innerHTML = '<div></div>'22 const div = fixtureEl.querySelector('div')23 EventHandler.on(div, 'click', () => {24 expect().nothing()25 done()26 })27 div.click()28 })29 it('should add namespaced event listener', done => {30 fixtureEl.innerHTML = '<div></div>'31 const div = fixtureEl.querySelector('div')32 EventHandler.on(div, 'bs.namespace', () => {33 expect().nothing()34 done()35 })36 EventHandler.trigger(div, 'bs.namespace')37 })38 it('should add native namespaced event listener', done => {39 fixtureEl.innerHTML = '<div></div>'40 const div = fixtureEl.querySelector('div')41 EventHandler.on(div, 'click.namespace', () => {42 expect().nothing()43 done()44 })45 EventHandler.trigger(div, 'click')46 })47 it('should handle event delegation', done => {48 EventHandler.on(document, 'click', '.test', () => {49 expect().nothing()50 done()51 })52 fixtureEl.innerHTML = '<div class="test"></div>'53 const div = fixtureEl.querySelector('div')54 div.click()55 })56 })57 describe('one', () => {58 it('should call listener just one', done => {59 fixtureEl.innerHTML = '<div></div>'60 let called = 061 const div = fixtureEl.querySelector('div')62 const obj = {63 oneListener() {64 called++65 }66 }67 EventHandler.one(div, 'bootstrap', obj.oneListener)68 EventHandler.trigger(div, 'bootstrap')69 EventHandler.trigger(div, 'bootstrap')70 setTimeout(() => {71 expect(called).toEqual(1)72 done()73 }, 20)74 })75 })76 describe('off', () => {77 it('should not remove a listener', () => {78 fixtureEl.innerHTML = '<div></div>'79 const div = fixtureEl.querySelector('div')80 EventHandler.off(div, null, () => {})81 EventHandler.off(null, 'click', () => {})82 expect().nothing()83 })84 it('should remove a listener', done => {85 fixtureEl.innerHTML = '<div></div>'86 const div = fixtureEl.querySelector('div')87 let called = 088 const handler = () => {89 called++90 }91 EventHandler.on(div, 'foobar', handler)92 EventHandler.trigger(div, 'foobar')93 EventHandler.off(div, 'foobar', handler)94 EventHandler.trigger(div, 'foobar')95 setTimeout(() => {96 expect(called).toEqual(1)97 done()98 }, 20)99 })100 it('should remove all the events', done => {101 fixtureEl.innerHTML = '<div></div>'102 const div = fixtureEl.querySelector('div')103 let called = 0104 EventHandler.on(div, 'foobar', () => {105 called++106 })107 EventHandler.on(div, 'foobar', () => {108 called++109 })110 EventHandler.trigger(div, 'foobar')111 EventHandler.off(div, 'foobar')112 EventHandler.trigger(div, 'foobar')113 setTimeout(() => {114 expect(called).toEqual(2)115 done()116 }, 20)117 })118 it('should remove all the namespaced listeners if namespace is passed', done => {119 fixtureEl.innerHTML = '<div></div>'120 const div = fixtureEl.querySelector('div')121 let called = 0122 EventHandler.on(div, 'foobar.namespace', () => {123 called++124 })125 EventHandler.on(div, 'foofoo.namespace', () => {126 called++127 })128 EventHandler.trigger(div, 'foobar.namespace')129 EventHandler.trigger(div, 'foofoo.namespace')130 EventHandler.off(div, '.namespace')131 EventHandler.trigger(div, 'foobar.namespace')132 EventHandler.trigger(div, 'foofoo.namespace')133 setTimeout(() => {134 expect(called).toEqual(2)135 done()136 }, 20)137 })138 it('should remove the namespaced listeners', done => {139 fixtureEl.innerHTML = '<div></div>'140 const div = fixtureEl.querySelector('div')141 let calledCallback1 = 0142 let calledCallback2 = 0143 EventHandler.on(div, 'foobar.namespace', () => {144 calledCallback1++145 })146 EventHandler.on(div, 'foofoo.namespace', () => {147 calledCallback2++148 })149 EventHandler.trigger(div, 'foobar.namespace')150 EventHandler.off(div, 'foobar.namespace')151 EventHandler.trigger(div, 'foobar.namespace')152 EventHandler.trigger(div, 'foofoo.namespace')153 setTimeout(() => {154 expect(calledCallback1).toEqual(1)155 expect(calledCallback2).toEqual(1)156 done()157 }, 20)158 })159 it('should remove the all the namespaced listeners for native events', done => {160 fixtureEl.innerHTML = '<div></div>'161 const div = fixtureEl.querySelector('div')162 let called = 0163 EventHandler.on(div, 'click.namespace', () => {164 called++165 })166 EventHandler.on(div, 'click.namespace2', () => {167 called++168 })169 EventHandler.trigger(div, 'click')170 EventHandler.off(div, 'click')171 EventHandler.trigger(div, 'click')172 setTimeout(() => {173 expect(called).toEqual(2)174 done()175 }, 20)176 })177 it('should remove the specified namespaced listeners for native events', done => {178 fixtureEl.innerHTML = '<div></div>'179 const div = fixtureEl.querySelector('div')180 let called1 = 0181 let called2 = 0182 EventHandler.on(div, 'click.namespace', () => {183 called1++184 })185 EventHandler.on(div, 'click.namespace2', () => {186 called2++187 })188 EventHandler.trigger(div, 'click')189 EventHandler.off(div, 'click.namespace')190 EventHandler.trigger(div, 'click')191 setTimeout(() => {192 expect(called1).toEqual(1)193 expect(called2).toEqual(2)194 done()195 }, 20)196 })197 it('should remove a listener registered by .one', done => {198 fixtureEl.innerHTML = '<div></div>'199 const div = fixtureEl.querySelector('div')200 const handler = () => {201 throw new Error('called')202 }203 EventHandler.one(div, 'foobar', handler)204 EventHandler.off(div, 'foobar', handler)205 EventHandler.trigger(div, 'foobar')206 setTimeout(() => {207 expect().nothing()208 done()209 }, 20)210 })211 it('should remove the correct delegated event listener', () => {212 const element = document.createElement('div')213 const subelement = document.createElement('span')214 element.appendChild(subelement)215 const anchor = document.createElement('a')216 element.appendChild(anchor)217 let i = 0218 const handler = () => {219 i++220 }221 EventHandler.on(element, 'click', 'a', handler)222 EventHandler.on(element, 'click', 'span', handler)223 fixtureEl.appendChild(element)224 EventHandler.trigger(anchor, 'click')225 EventHandler.trigger(subelement, 'click')226 // first listeners called227 expect(i).toEqual(2)228 EventHandler.off(element, 'click', 'span', handler)229 EventHandler.trigger(subelement, 'click')230 // removed listener not called231 expect(i).toEqual(2)232 EventHandler.trigger(anchor, 'click')233 // not removed listener called234 expect(i).toEqual(3)235 EventHandler.on(element, 'click', 'span', handler)236 EventHandler.trigger(anchor, 'click')237 EventHandler.trigger(subelement, 'click')238 // listener re-registered239 expect(i).toEqual(5)240 EventHandler.off(element, 'click', 'span')241 EventHandler.trigger(subelement, 'click')242 // listener removed again243 expect(i).toEqual(5)244 })245 })...

Full Screen

Full Screen

ChangeHandlerMediator-dbg.js

Source:ChangeHandlerMediator-dbg.js Github

copy

Full Screen

1/*!2 * UI development toolkit for HTML5 (OpenUI5)3 * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company.4 * Licensed under the Apache License, Version 2.0 - see LICENSE.txt.5 */6sap.ui.define([7 "jquery.sap.global"8], function(9 jQuery10) {11 "use strict";12 /**13 * Change Handler Mediator to manage the requirements for the change handlers14 *15 * @alias sap.ui.fl.changeHandler.ChangeHandlerMediator16 *17 * @private18 * @author SAP SE19 * @version 1.50.520 *21 * @experimental Since 1.49.0 This class is experimental and provides only limited functionality. Also the API might be22 * changed in future.23 *24 */25 var ChangeHandlerMediator = { };26 /**27 * Array of relevant change handlers settings28 * Initialize with the required entries for AddODataField29 */30 ChangeHandlerMediator._aChangeHandlerSettings = [];31 ["addODataField", "addODataFieldWithLabel"].forEach(function (sScenario) {32 ["2.0", "1.0"].forEach(function (sVersion) {33 ChangeHandlerMediator._aChangeHandlerSettings.push({34 key: {35 "scenario": sScenario,36 "oDataServiceVersion": sVersion37 },38 content: {39 "requiredLibraries": {40 "sap.ui.comp": {41 "minVersion": "1.48",42 "lazy": false43 }44 }45 },46 scenarioInitialized: false47 });48 });49 });50 /**51 * Add change handler settings to the mediated list52 * @param {Object} mKey Collection of keys53 * @param {string} mKey.scenario The scenario name54 * @param {Object} mSettings The relevant settings for the change handler55 */56 ChangeHandlerMediator.addChangeHandlerSettings = function(mKey, mSettings) {57 var mNewChangeHandlerSettings;58 if (!(mKey && mSettings)){59 throw new Error('New entry in ChangeHandlerMediator requires a key and settings');60 }61 mNewChangeHandlerSettings = {62 key : mKey,63 content : mSettings,64 scenarioInitialized : false65 };66 var mExistingChangeHandlerSettings = this.getChangeHandlerSettings(mKey, true);67 var iIndex = this._aChangeHandlerSettings.indexOf(mExistingChangeHandlerSettings);68 // If entry already exists, extend existing content and set initialized to false69 if (iIndex > -1) {70 jQuery.extend(this._aChangeHandlerSettings[iIndex].content,71 mNewChangeHandlerSettings.content);72 this._aChangeHandlerSettings[iIndex].scenarioInitialized = false;73 } else {74 this._aChangeHandlerSettings.push(mNewChangeHandlerSettings);75 this._createChangeHandlerSettingsGetter(mNewChangeHandlerSettings);76 }77 };78 /**79 * Retrieves change handler settings from the mediated list80 * @param {Object} mKey Collection of keys81 * @param {boolean} bSkipInitialization If true, the scenario should not be initialized82 * @return {Object} The change handler settings83 */84 ChangeHandlerMediator.getChangeHandlerSettings = function(mKey, bSkipInitialization){85 var aKeys = Object.keys(mKey);86 var mFoundChangeHandlerSettings;87 if (aKeys.length > 0) {88 mFoundChangeHandlerSettings = this._aChangeHandlerSettings.filter(function(oEntry, iIndex){89 var aExistingKeys = Object.keys(oEntry.key);90 if (aExistingKeys.length === aKeys.length) {91 var aMatchingKeys = aKeys.filter(function(sKey){92 if (oEntry.key[sKey] === mKey[sKey]){93 return true;94 }95 });96 // Only return the object with the exact matching keys97 if (aMatchingKeys.length === aKeys.length){98 return true;99 }100 }101 })[0];102 // Try to initialize the corresponding scenario103 if (!bSkipInitialization && mFoundChangeHandlerSettings104 && !mFoundChangeHandlerSettings.scenarioInitialized) {105 mFoundChangeHandlerSettings.scenarioInitialized106 = this._initializeScenario(mFoundChangeHandlerSettings);107 }108 }109 if (bSkipInitialization ||110 (mFoundChangeHandlerSettings && mFoundChangeHandlerSettings.scenarioInitialized)){111 return mFoundChangeHandlerSettings;112 }113 };114 /**115 * Initializes a scenario that is required by the application116 * (e.g. for AddODataField -> load the required libraries)117 * @param {Object} mFoundChangeHandlerSettings The Change Handler Settings for the scenario118 * @return {boolean} true if properly initialized119 */120 ChangeHandlerMediator._initializeScenario = function(mFoundChangeHandlerSettings){121 var sLibraryName;122 if (mFoundChangeHandlerSettings.content.requiredLibraries){123 try {124 var aLibraries = Object.keys(mFoundChangeHandlerSettings.content.requiredLibraries);125 aLibraries.forEach(function(sLibrary){126 sLibraryName = sLibrary;127 sap.ui.getCore().loadLibrary(sLibrary);128 });129 var iIndex = this._aChangeHandlerSettings.indexOf(mFoundChangeHandlerSettings);130 // Update the entry on the array131 this._aChangeHandlerSettings[iIndex].scenarioInitialized = true;132 return true;133 } catch (e){134 jQuery.sap.log.warning("Required library not available: " + sLibraryName + " - "135 + mFoundChangeHandlerSettings.key.scenario + " could not be initialized");136 return false;137 }138 }139 };140 ChangeHandlerMediator._createChangeHandlerSettingsGetter = function(mChangeHandlerSettings){141 var sGetterName = 'get' + jQuery.sap.charToUpperCase(mChangeHandlerSettings.key.scenario) + 'Settings';142 if (!ChangeHandlerMediator[sGetterName]) {143 /**144 * Retrieves the settings for the specified scenario, getting the oData145 * service version from the control and ensures that a create function is146 * available for the change handler147 * @param {sap.ui.core.Control} oControl The control for the scenario148 * @return {Object} The Change Handler Settings for the scenario149 */150 ChangeHandlerMediator[sGetterName] = function(oControl){151 var sODataServiceVersion;152 var mFoundChangeHandlerSettings;153 try {154 sODataServiceVersion = oControl.getModel().getMetaModel().getProperty("/dataServices/dataServiceVersion");155 } catch (e) {156 jQuery.sap.log.warning("Data service version could not be retrieved");157 }158 mFoundChangeHandlerSettings = this.getChangeHandlerSettings({159 "scenario" : mChangeHandlerSettings.key.scenario,160 "oDataServiceVersion" : sODataServiceVersion161 });162 // Without a create function, the settings should not be returned163 if (mFoundChangeHandlerSettings &&164 mFoundChangeHandlerSettings.content &&165 mFoundChangeHandlerSettings.content.createFunction){166 return mFoundChangeHandlerSettings;167 }168 };169 }170 };171 // Create getters172 ChangeHandlerMediator._aChangeHandlerSettings.forEach(function (mChangeHandlerSettings) {173 ChangeHandlerMediator._createChangeHandlerSettingsGetter(mChangeHandlerSettings);174 });175 return ChangeHandlerMediator;...

Full Screen

Full Screen

DomEventMixin.js

Source:DomEventMixin.js Github

copy

Full Screen

1if (typeof window.RadControlsNamespace == "undefined")2{3 window.RadControlsNamespace = {};4}5if (6 typeof(window.RadControlsNamespace.DomEventMixin) == "undefined" ||7 typeof(window.RadControlsNamespace.DomEventMixin.Version) == null ||8 window.RadControlsNamespace.DomEventMixin.Version < 39 )10{ 11 12 RadControlsNamespace.DomEventMixin = 13 {14 Version : 3, // Change the version when make changes. Change the value in the IF also15 16 Initialize : function(obj)17 {18 obj.CreateEventHandler = this.CreateEventHandler;19 obj.AttachDomEvent = this.AttachDomEvent;20 obj.DetachDomEvent = this.DetachDomEvent;21 obj.DisposeDomEventHandlers = this.DisposeDomEventHandlers;22 obj._domEventHandlingEnabled = true;23 obj.EnableDomEventHandling = this.EnableDomEventHandling;24 obj.DisableDomEventHandling = this.DisableDomEventHandling;25 26 obj.RemoveHandlerRegister = this.RemoveHandlerRegister;27 obj.GetHandlerRegister = this.GetHandlerRegister;28 obj.AddHandlerRegister = this.AddHandlerRegister;29 obj.handlerRegisters = [];30 },31 32 EnableDomEventHandling : function ()33 {34 this._domEventHandlingEnabled = true;35 },36 37 DisableDomEventHandling : function ()38 {39 this._domEventHandlingEnabled = false;40 },41 42 CreateEventHandler : function (methodName, fireIfDisabled)43 {44 var instance = this;45 return function (e)46 {47 if (!instance._domEventHandlingEnabled && !fireIfDisabled)48 {49 return;50 }51 52 return instance[methodName](e || window.event);53 }54 },55 56 AttachDomEvent : function(element, eventName, eventHandlerName, fireIfDisabled)57 {58 var eventHandler = this.CreateEventHandler(eventHandlerName, fireIfDisabled);59 // if such entry exist already - detach it first60 var oldRegister = this.GetHandlerRegister(element, eventName, eventHandlerName);61 if (oldRegister != null)62 {63 this.DetachDomEvent(oldRegister.Element, oldRegister.EventName, eventHandlerName);64 }65 66 // register the new entry67 var eventRegister = { 68 "Element" : element, 69 "EventName" : eventName, 70 "HandlerName" : eventHandlerName, 71 "Handler" : eventHandler 72 };73 this.AddHandlerRegister(eventRegister);74 75 // now do the "real" job76 if (element.addEventListener)77 {78 element.addEventListener(eventName, eventHandler, false);79 }80 else if (element.attachEvent)81 {82 element.attachEvent("on" + eventName, eventHandler);83 }84 },85 86 87 DetachDomEvent : function(element, eventName, eventHandler)88 {89 var eventRegister = null;90 var eventHandlerName = "";91 if (typeof eventHandler == "string") 92 {93 eventHandlerName = eventHandler;94 eventRegister = this.GetHandlerRegister(element, eventName, eventHandlerName);95 if(eventRegister == null)96 return;97 eventHandler = eventRegister.Handler;98 }99 100 if (!element)101 {102 return;103 }104 105 if (element.removeEventListener)106 {107 element.removeEventListener(eventName, eventHandler, false);108 }109 else if (element.detachEvent)110 {111 element.detachEvent("on" + eventName, eventHandler);112 }113 114 if (eventRegister != null && eventHandlerName != "")115 {116 this.RemoveHandlerRegister(eventRegister);117 eventRegister = null;118 }119 },120 121 DisposeDomEventHandlers : function()122 {123 for (var i=0; i < this.handlerRegisters.length; i ++)124 {125 var eventRegister = this.handlerRegisters[i];126 if (eventRegister != null)127 {128 this.DetachDomEvent(129 eventRegister.Element, 130 eventRegister.EventName, 131 eventRegister.Handler);132 }133 }134 135 this.handlerRegisters = [];136 },137 RemoveHandlerRegister : function(eventRegister)138 {139 try {140 var regIndex = eventRegister.index;141 for (var i in eventRegister)142 {143 eventRegister[i] = null;144 }145 this.handlerRegisters[regIndex] = null;146 } catch (e) {}147 },148 GetHandlerRegister : function(element, eventName, handlerName)149 {150 for (var i=0; i < this.handlerRegisters.length; i ++)151 {152 var eventRegister = this.handlerRegisters[i];153 if (eventRegister != null &&154 eventRegister.Element == element && 155 eventRegister.EventName == eventName &&156 eventRegister.HandlerName == handlerName 157 )158 {159 return this.handlerRegisters[i];160 }161 }162 163 return null;164 },165 166 AddHandlerRegister : function(props)167 {168 props.index = this.handlerRegisters.length;169 this.handlerRegisters[this.handlerRegisters.length] = props;170 }171 }172 173 RadControlsNamespace.DomEvent = {};174 175 RadControlsNamespace.DomEvent.PreventDefault = function (e)176 {177 if (!e) return true;178 179 if (e.preventDefault)180 {181 e.preventDefault();182 }183 184 e.returnValue = false;185 return false;186 }187 188 RadControlsNamespace.DomEvent.StopPropagation = function (e)189 {190 if (!e) return;191 192 if (e.stopPropagation)193 {194 e.stopPropagation();195 }196 else197 {198 e.cancelBubble = true;199 }200 }201 202 RadControlsNamespace.DomEvent.GetTarget = function (e)203 {204 if (!e) return null;205 206 return e.target || e.srcElement;207 }208 209 210 RadControlsNamespace.DomEvent.GetRelatedTarget = function (e)211 {212 if (!e) return null;213 214 return e.relatedTarget || (e.type == "mouseout" ? e.toElement : e.fromElement);215 }216 217 RadControlsNamespace.DomEvent.GetKeyCode = function (e)218 {219 if (!e) return 0;220 221 return e.which || e.keyCode;222 }223}224//BEGIN_ATLAS_NOTIFY225if (typeof(Sys) != "undefined")226{227 if (Sys.Application != null && Sys.Application.notifyScriptLoaded != null)228 {229 Sys.Application.notifyScriptLoaded();230 }231}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { launch } = require('qawolf');2const selectors = require('../selectors/test');3describe('test', () => {4 let browser;5 let page;6 beforeAll(async () => {7 browser = await launch();8 page = await browser.newPage();9 });10 afterAll(() => browser.close());11 it('test', async () => {12 await page.waitForSelector(selectors['#searchInput']);13 await page.click(selectors['#searchInput']);14 await page.type(selectors['#searchInput'], 'Hello World');15 await page.click(selectors['#searchButton']);16 });17});18import { launch, selectors } from 'qawolf';19describe('test', () => {20 let browser;21 let page;22 beforeAll(async () => {23 browser = await launch();24 page = await browser.newPage();25 });26 afterAll(() => browser.close());27 it('test', async () => {28 await page.waitForSelector(selectors['#searchInput']);29 await page.click(selectors['#searchInput']);30 await page.type(selectors['#searchInput'], 'Hello World');31 await page.click(selectors['#searchButton']);32 });33});34import { launch, selectors } from 'qawolf';35describe('test', () => {36 let browser;37 let page;38 beforeAll(async () => {39 browser = await launch();40 page = await browser.newPage();41 });42 afterAll(() => browser.close());43 it('test', async () => {44 await page.waitForSelector(selectors['#searchInput']);45 await page.click(selectors['#searchInput']);46 await page.type(selectors['#searchInput'], 'Hello World');47 await page.click(selectors['#searchButton']);48 });49});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { launch } = require("qawolf");2const selectors = require("../selectors/test.json");3describe("test", () => {4 let browser;5 let page;6 beforeAll(async () => {7 browser = await launch();8 page = await browser.newPage();9 });10 afterAll(async () => {11 await browser.close();12 });13 it("test", async () => {14 await page.click(selectors["q"]);15 await page.fill(selectors["q"], "test");16 await page.press(selectors["q"], "Enter");17 await page.waitForSelector(selectors["#search"]);18 });19});20{21}22module.exports = {23};24### `launch([options])`25const { launch } = require("qawolf");26const browser = await launch();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { qawolf } = require("qawolf");2const { firefox } = require("playwright");3(async () => {4 const browser = await firefox.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await qawolf.register(page);

Full Screen

Using AI Code Generation

copy

Full Screen

1const qawolf = require("qawolf");2const selectors = require("./selectors/test.json");3let browser;4let page;5beforeAll(async () => {6 browser = await qawolf.launch();7});8beforeEach(async () => {9});10afterEach(async () => {11 await qawolf.stopVideos();12 await page.close();13});14afterAll(async () => {15 await browser.close();16});17test("test",

Full Screen

Using AI Code Generation

copy

Full Screen

1const qawolf = require('qawolf');2const { launch } = qawolf;3const path = require('path');4const page = await browser.newPage();5const input = await page.$('input[name="name"]');6const button = await page.$('button');7await input.type('John Smith');8await button.click();9await page.save(path.join(__dirname, 'test.html'));10await browser.close();11### launch(options)12 - `args` <[Array]<[string]>> List of Chromium arguments to pass to the browser. The browser will be launched with `--disable-extensions` by default. If you are using [Puppeteer](

Full Screen

Using AI Code Generation

copy

Full Screen

1const { handler } = require("./qawolf");2module.exports = async (context, req) => {3 await handler(context, req);4};5const qawolf = require("qawolf");6const { chromium } = require("playwright");7module.exports.handler = async (context, req) => {8 const browser = await chromium.launch();9 const context = await browser.newContext();10 await qawolf.click(page, "#root > div > div > div:nth-child(2) > button");11 await qawolf.type(page, "#root > div > div > div:nth-child(2) > input", "hi");12 await qawolf.click(page, "#root > div > div > div:nth-child(2) > button");13 await browser.close();14};15{16 "scripts": {17 },18 "dependencies": {19 },20 "devDependencies": {21 }22}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { handler } = require('qawolf');2const browser = await handler();3const page = await browser.newPage();4await page.type('[placeholder="Enter your name"]', 'John');5await page.click('[placeholder="Enter your email"]');6await page.type('[placeholder="Enter your email"]', '

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run qawolf automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful