//board elements/variables
let boardArray;
let boardDisplay;
let board;
let boardWidth;
let boardHeight;
let highLightedX;
let highLightedY;
let boardTranslationX;
let cellWidth;
let gridLength;
let gridHeight;
let numberSize;

//display elements
let displayTxt; //the you win/lose text
let title;
let achievementScreen;

//buttons
let gameButtons;
let menuButtons;
let playAgainBtn;
let homeBtn;
let achievementsBtn;
let musicBtn;
let easyBtn;
let mediumBtn;
let hardBtn;

//music variables
let musicPlaying = true; //is for keeping track of the music button
let isPlayingMusic = false; //is for keeping track of if we started the music by interacting with the window (we can only play things once they've clicked the screen)
let backgroundMusic = new Audio("soundEffetcs/backgroundMusic.mp3");

//the top of screen UI
let sidebar;
let flagTxt;
let timerTxt;
let flagNum;

//gameplay variables
let gameMode;
let bombsNeeded;
let firstClick = true;
let hasLost = false;
let hasWon = false;
let isPlaying = false;
let placedFlag = false;
let cheatActive = false;
let sequence = 0; //keeps track of the step we are on in the cheat code

//timer varibles
let timer = null;
let startTime = 0;
let timePassed = 0;

//achievement popup elements
let popupContainer;
let popupTxt;
let popupImg;
let popupsRunning = 0; //keeps track of how many popups are running at once (so we can delay them)
let popupDelay = 0; //keeps track of the delay needed in ms

//achivement display elements (right side of the screen)
let displayAchievement;
let achievementsDescription;
let achievementsTitle;

//achievement elements (are buttons so we can track mouse movements)
let apperenticeSweeper;
let hexOfDanger;
let rapidResponse;
let photographicMemory;
let unmarkedTerritory;
let IntermediateIntel;
let luckySeven;
let masterOfTime;
let sixSeven;
let masterDeminer;
let totalIsolation;
let pureLogic;
let bombTechnician;
let highFive;
let beginnersLuck;
let questionMark;

//achievement image elements (used for the buttons)
let apperenticeSweeperImg;
let hexOfDangerImg;
let rapidResponseImg;
let photographicMemoryImg;
let unmarkedTerritoryImg;
let IntermediateIntelImg;
let luckySevenImg;
let masterOfTimeImg;
let sixSevenImg;
let masterDeminerImg;
let totalIsolationImg;
let pureLogicImg;
let bombTechnicianImg;
let highFiveImg;
let beginnersLuckImg;
let questionMarkImg;

//variables to store achevements
let hasApperenticeSweeper = false;
let hasHexOfDanger = false;
let hasRapidResponse = false;
let hasPhotographicMemory = false;
let hasUnmarkedTerritory = false;
let hasIntermediateIntel = false;
let hasLuckySeven = false;
let hasMasterOfTime = false;
let hasSixSeven = false;
let hasMasterDeminer = false;
let hasTotalIsolation = false;
let hasPureLogic = false;
let hasBombTechnician = false;
let hasHighFive = false;
let hasBeginnersLuck = false;
let hasQuestionMark = false;


window.addEventListener("load", function(){
    //loads all the elements
    loadElements();

    //check local storage for achievement data
    checkAchievementStorage();

    // lines 133-300 used for the achievement screen, as all the items are buttons, we display the text, image, and title of the achievement
    apperenticeSweeper.addEventListener("mousemove", function(){
        if(hasApperenticeSweeper){
            displayAchievement.src = "Minesweeper Achievements/apperenticeSweeper.png";
        }
        else{
            displayAchievement.src = "Minesweeper Achievements/greyApperenticeSweeper.png";
        }
        achievementsTitle.innerHTML = "Apperentice Sweeper";
        achievementsDescription.innerHTML = "Given for clearing easy mode";
    })
    IntermediateIntel.addEventListener("mousemove", function(){
        if(hasIntermediateIntel){
             displayAchievement.src = "Minesweeper Achievements/IntermediateIntel.png";
        }
        else{
            displayAchievement.src = "Minesweeper Achievements/greyIntermediateIntel.png";
        }
        achievementsTitle.innerHTML = "Intermediate Intel";
        achievementsDescription.innerHTML = "Given for clearing medium mode";
    })
    masterDeminer.addEventListener("mousemove", function(){
        if(hasMasterDeminer){
            displayAchievement.src = "Minesweeper Achievements/masterDeminer.png";
        }
       else{
           displayAchievement.src = "Minesweeper Achievements/greyMasterDeminer.png";
        }
        achievementsTitle.innerHTML = "Master Deminer";
        achievementsDescription.innerHTML = "Given for clearing hard mode";
    })
    highFive.addEventListener("mousemove", function(){
        if(hasHighFive){
        displayAchievement.src = "Minesweeper Achievements/highFive.png";
        }
       else{
            displayAchievement.src = "Minesweeper Achievements/greyHighFive.png";
        }
        achievementsTitle.innerHTML = "High Five";
        achievementsDescription.innerHTML = "Given for uncovering a 5"
    })
    hexOfDanger.addEventListener("mousemove", function(){
        if(hasHighFive){
            displayAchievement.src = "Minesweeper Achievements/hexOfDanger.png";
            }
        else{
            displayAchievement.src = "Minesweeper Achievements/greyHexOfDanger.png";
        }
    
        achievementsTitle.innerHTML = "Hex Of Danger";
        achievementsDescription.innerHTML = "Given for uncovering a 6";
    })
    luckySeven.addEventListener("mousemove", function(){
        if(hasLuckySeven){
            displayAchievement.src = "Minesweeper Achievements/luckySeven.png";
            }
        else{
            displayAchievement.src = "Minesweeper Achievements/greyLuckySeven.png";
        }
        achievementsTitle.innerHTML = "Luckey Seven";
        achievementsDescription.innerHTML = "Given for uncovering a 7";
    })
    totalIsolation.addEventListener("mousemove", function(){
        if(hasTotalIsolation){
            displayAchievement.src = "Minesweeper Achievements/totalIsolation.png";
            }
        else{
            displayAchievement.src = "Minesweeper Achievements/greyTotalIsolation.png";
        }
        
        achievementsTitle.innerHTML = "Total Isolation";
        achievementsDescription.innerHTML = "Given for uncovering a 8";
    })
    beginnersLuck.addEventListener("mousemove", function(){
        if(hasBeginnersLuck){
            displayAchievement.src = "Minesweeper Achievements/beginnersLuck.png";
            }
        else{
            displayAchievement.src = "Minesweeper Achievements/greyBeginnersLuck.png";
        }
        achievementsTitle.innerHTML = "Beginners Luck";
        achievementsDescription.innerHTML = "Given for clearing easy mode in less than 10 seconds";
        
    })
    rapidResponse.addEventListener("mousemove", function(){
        if(hasRapidResponse){
            displayAchievement.src = "Minesweeper Achievements/rapidResponse.png";
            }
        else{
            displayAchievement.src = "Minesweeper Achievements/greyRapidResponse.png";
        }
        
        achievementsTitle.innerHTML = "Rapid Response";
        achievementsDescription.innerHTML = "Given for clearing medium mode in less than 2 minutes";
    })
    masterOfTime.addEventListener("mousemove", function(){
        if(hasMasterOfTime){
            displayAchievement.src = "Minesweeper Achievements/masterOfTime.png";
            }
        else{
            displayAchievement.src = "Minesweeper Achievements/greyMasterOfTime.png";
        }
     
        achievementsTitle.innerHTML = "Master Of Time";
        achievementsDescription.innerHTML = "Given for clearing hard mode in less than 5 minutes";
    })
    pureLogic.addEventListener("mousemove", function(){
        if(hasPureLogic){
            displayAchievement.src = "Minesweeper Achievements/pureLogic.png";
            }
        else{
            displayAchievement.src = "Minesweeper Achievements/greyPureLogic.png";
        }
  
        achievementsTitle.innerHTML = "Pure Logic";
        achievementsDescription.innerHTML = "Given for clearing easy mode without placing a flag";
    })
    unmarkedTerritory.addEventListener("mousemove", function(){
        if(hasUnmarkedTerritory){
            displayAchievement.src = "Minesweeper Achievements/unmarkedTerritory.png";
            }
        else{
            displayAchievement.src = "Minesweeper Achievements/greyUnmarkedTerritory.png";
        }
        achievementsTitle.innerHTML = "Unmarked Territory";
        achievementsDescription.innerHTML = "Given for clearing medium mode without placing a flag";
    })
    photographicMemory.addEventListener("mousemove", function(){
        if(hasPhotographicMemory){
            displayAchievement.src = "Minesweeper Achievements/photographicMemory.png";
            }
        else{
            displayAchievement.src = "Minesweeper Achievements/greyPhotographicMemory.png";
        }
        achievementsTitle.innerHTML = "Photographic Memory";
        achievementsDescription.innerHTML = "Given for clearing hard mode without placing a flag";
    })
    sixSeven.addEventListener("mousemove", function(){
        if(hasSixSeven){
            displayAchievement.src = "Minesweeper Achievements/67.png";
            }
        else{
            displayAchievement.src = "Minesweeper Achievements/grey67.png";
        }
        
        achievementsTitle.innerHTML = "6 7";
        achievementsDescription.innerHTML = "Given for finding a 6 and 7 next to each other";
    })
    bombTechnician.addEventListener("mousemove", function(){
        if(hasBombTechnician){
            displayAchievement.src = "Minesweeper Achievements/bombTechnician.png";
            }
        else{
            displayAchievement.src = "Minesweeper Achievements/greyBombTechnician.png";
        }
        
        achievementsTitle.innerHTML = "Bomb Technician";
        achievementsDescription.innerHTML = "Given for beating hard mode in less than 5 minutes without placing a flag";
    })
    questionMark.addEventListener("mousemove", function(){
        if(hasQuestionMark){
            displayAchievement.src = "Minesweeper Achievements/questionMark.png";
            achievementsDescription.innerHTML = "Given by activating the cheat code";
            }
        else{
            displayAchievement.src = "Minesweeper Achievements/greyQuestionMark.png";
            achievementsDescription.innerHTML = "?";
        }
        
        achievementsTitle.innerHTML = "?";
        
    })

    //when the mouse moves over the board
    board.addEventListener("mousemove", function(e){ 
        
        //freeze the highlight if they have won or lost
        if(!hasLost && !hasWon){
            //find board width and hieght
            boardWidth = getBoardWidth();
            boardHeight = getBoardHieght();

            //get mouse position
            const mouseX = e.clientX-(boardWidth*boardTranslationX); 
            const mouseY = (5.5*window.innerWidth/100)+boardHeight-(e.clientY); //the 5.5 is for the boards top margin

            //finds the square position of the mouse
            let squareX = squareClicked(mouseX,boardWidth, gridLength);
            let squareY = squareClicked(mouseY,boardHeight, gridHeight);

            //if the mouse is on the board highlight the square (without the if the highlight comes up on the left)
            if(mouseX>0){
                highlightSquare(squareX,squareY,boardWidth);
            }
        }
    })

    //when we click the board, this will run
    board.addEventListener("click", function(e) { 
        
        //only lets them click the board if they haven't lost or won
        //is playing is because the board is still technically there on the home screen, so clicking in an empty space causes a problem where they win
        if(!hasLost && !hasWon && isPlaying){
            //find board width and height
            boardWidth = getBoardWidth();
            boardHeight = getBoardHieght();
        
            //get mouse position
            const mouseX = e.clientX-(boardWidth*boardTranslationX);  
            const mouseY = (5.5*window.innerWidth/100)+boardHeight-(e.clientY); //the 5.5 is for the boards top margin

            //finds the square position of the mouse
            let squareX = squareClicked(mouseX,boardWidth, gridLength);
            let squareY = squareClicked(mouseY,boardHeight, gridHeight);

    
            if(firstClick){ //runs only on the first click (makes board)
                firstClick = false;

                //create board around the first click (so that they don't click a bomb or have an impossible start)
                createBoard(squareX, squareY);
                renderBoard();

                //start the timer
                startTimer();

                //play some breaking sounds
                diggingSound(3);
                diggingSound(2);
                diggingSound(1);
            }
            else{
                //find the square we clicked
                let squareClicked = boardArray[squareY-1][squareX-1];

                //if it is empty (has no bombs or info, aka a green tile)
                if(squareClicked == "empty"){
                    //switch it with safe (will show the number)
                    boardArray[squareY-1].splice((squareX-1),1, "safe");

                    //find how many bombs are near it
                    let bombNumber = findBombNumber(squareY-1,squareX-1);

                    //play the dig sound depending on the number
                    diggingSound(bombNumber);

                    //if it's a 0, we will break the ones around it and continue if there are more fully safe ones
                    if(bombNumber == 0){
                        branchOut();

                        //play some breaking sounds
                        diggingSound(3);
                        diggingSound(2);
                        diggingSound(1);
                    }
                   
                }
                //if we hit a bomb
                else if(squareClicked == "bomb"){
                    //set that we've lost, stop the timer and display the 'game over' text
                    hasLost = true;
                    stopTimer();
                    displayTxt.innerHTML = "Game Over!";
                    displayTxt.style.borderWidth = "3px";
                    playAgainBtn.innerHTML = "Try Again";
                    bombSound();
                }
                //if we click a flag, remove the flag
                else if(squareClicked == "flagBomb"){
                    boardArray[squareY-1].splice((squareX-1),1, "bomb");
        
                }
                else if (squareClicked == "flag"){
                    boardArray[squareY-1].splice((squareX-1),1, "empty");
                }

                //render the new board (with the change we just made)
                renderBoard();
            } 
        }
    })

    //when a key is clicked
    document.addEventListener('keydown', (event) => {
        //if space is pressed
        if (event.code === 'Space' && !firstClick) {
          
            //find the square we are over/highlighting
            let squareX = highLightedX;
            let squareY = highLightedY;
            let squareClicked = boardArray[squareY-1][squareX-1];

            //add a flag at that spot
            if(squareClicked == "empty"){
                boardArray[squareY-1].splice((squareX-1),1, "flag");
                //set that we've placed a flag (for achivements)
                placedFlag = true;
                flagSound();
            }
            else if(squareClicked == "bomb"){
                boardArray[squareY-1].splice((squareX-1),1, "flagBomb");
                //set that we've placed a flag (for achivements)
                placedFlag = true;
                flagSound();
            }

            //if there is already a flag, remove it instead
            else if(squareClicked == "flagBomb"){
                boardArray[squareY-1].splice((squareX-1),1, "bomb");
                flagSound();
            }
            else if(squareClicked == "flag"){
                boardArray[squareY-1].splice((squareX-1),1, "empty");
                flagSound();
            }

            //render the new board
            renderBoard();
        }

        //track imputs for cheatcode/easterEgg
        else if (event.code === 'ArrowUp') {
            if(sequence == 0 || sequence == 1){
                sequence++;
            }
            else if(sequence ==2){
                sequence = 2; //keep it at the end of the up keys if they cliked it 3 times in a row
            }
            else{
                sequence = 1;
            }
        }
        else if (event.code === 'ArrowDown') {
            if(sequence == 2 || sequence == 3){
                sequence++;
            }
            else{
                sequence = 0;
            }
        }
        else if (event.code === 'ArrowLeft') {
            if(sequence == 4 || sequence == 6){
                sequence++;
            }
            else{
                sequence = 0;
            }
        }
        else if (event.code === 'ArrowRight') {
            if(sequence == 5 || sequence == 7){
                sequence++;
            }
            else{
                sequence = 0;
            }
        }
       else if (event.key === 'a' || event.key === 'A') {
            if(sequence == 9){
                sequence++;
            }
            else{
                sequence = 0;
            }
        }
        else if (event.key === 'b' || event.key === 'B') {
            if(sequence == 8){
                sequence++;
            }
            else{
                sequence = 0;
            }
        }

        else if (event.code === 'Enter') {
            //activate cheatcode
            if(sequence == 10 && isPlaying){ //only activeate cheatcode if we are playing 
                cheatActive = true;

                //if we don't have the secret achievment yet, give it to them
                if(!hasQuestionMark){
                    localStorage.setItem("questionMarkKey", "true"); //set it in local storage

                    popupDelay = popupsRunning * 3300;
                    popupsRunning++;
                    //pop up the achievement, after a delay if needed
                    setTimeout(popup, popupDelay, "?" , "Minesweeper Achievements/questionMark.png");

                    //set achievement
                    checkAchievementStorage();
                }

                //render the board with bombs
                renderBoard();
            }
            else{
                sequence = 0;
            }

        }
        else{ //if we clicked a random key
            sequence = 0;
        }


    });

    easyBtn.addEventListener("click", function(){
        //set easy mode options and start the game
        gameMode = "easy";
        gridLength = 8;
        gridHeight = 8;
        cellWidth = "5vw";
        bombsNeeded = 10;
        flagNum = 10;
        flagTxt.innerHTML = flagNum;
        boardTranslationX = 0.75;
        numberSize = 1.5
        startGame();
        clickSound();

    })

    mediumBtn.addEventListener("click", function(){
        //set medium mode options and start the game
        gameMode = "medium";
        gridLength = 16;
        gridHeight = 16;
        cellWidth = "2.5vw";
        bombsNeeded = 40;
        flagNum = 40;
        flagTxt.innerHTML = flagNum;
        boardTranslationX = 0.75;
        numberSize = 1
        startGame();
        clickSound();
    })

    hardBtn.addEventListener("click", function(){
        //set hard mode options and start the game
        gameMode = "hard";
        gridLength = 30;
        gridHeight = 16;
        cellWidth = "2.5vw";
        bombsNeeded = 99;
        flagNum = 99;
        flagTxt.innerHTML = flagNum;
        boardTranslationX = 0.167;
        numberSize = 1
        startGame();
        clickSound();
    })

    playAgainBtn.addEventListener("click", function(){
        //reset game
        startGame();
        clickSound();
    })

    homeBtn.addEventListener("click", function(){
        //set visibilities for the home page
        isPlaying = false;

        achievementScreen.style.visibility = "hidden";
        menuButtons.style.visibility = "visible";
        gameButtons.style.visibility = "hidden";
        sidebar.style.visibility = "hidden";
        board.style.visibility = "hidden";
        displayTxt.innerHTML = "";
        title.style.visibility = "visible";
        displayTxt.style.borderWidth = "0px";
    

        homeBtn.style.marginTop = "0vw";
        homeBtn.style.marginLeft = "0vw";
        homeBtn.style.visibility = "hidden";

        clickSound();
      
    })

    achievementsBtn.addEventListener("click", function(){
        //set visibilities for the achivement page
        menuButtons.style.visibility = "hidden";
        board.style.visibility = "hidden";
        achievementScreen.style.visibility = "visible";
        title.style.visibility = "hidden";

        homeBtn.style.marginTop = "-5vw";
        homeBtn.style.marginLeft = "47.5vw";
        homeBtn.style.visibility = "visible";

        clickSound();


    })

    resetAchievementsBtn.addEventListener("click", function(){
        //clear the storage
        localStorage.clear();
        clickSound();
        
        //clears the achivments in the current page (otherwise they have to refresh to see changes)
        resetAchievements();
    })

    musicBtn.addEventListener("click", function(){
        //if we are playing music
        if(musicPlaying && isPlayingMusic){ //'is playing music' is needed for if they're first click in the program is on the button, in which case it won't stop the music
            //stop it and change the text
            stopMusic();
            musicBtn.innerHTML = "Play Music";
            musicPlaying = false;
        }
        else{ //if we are not playing music
            //start it again and change text
            playMusic();
            musicBtn.innerHTML = "Stop Music";
            musicPlaying = true;
        }
        clickSound();
    })

    window.addEventListener("click", function(){
        //only plays the music once we click the screen (to avoid errors)
        if(!isPlayingMusic){
            isPlayingMusic = true;
            playMusic();
        }
    })


})

//slides the popup on screen with the achievement
function popup(title, path) {

    //set the title and path of the achievement
    popupTxt.innerHTML = title;
    popupImg.src = path;

    //slide it on screen
    popupContainer.style.transform = "translateX(-31vw)";

    //slide it back off after 2 seconds
    setTimeout(moveBack, 2000);
}

//slide the popup back off of the screen
function moveBack(){
    popupContainer.style.transform = "translateX(0vw)";
    
    //decrease the popup delay
    popupsRunning--;
    popupDelay = popupsRunning * 3300;
}

function startGame(){
    //set visibilities
    displayTxt.innerHTML = "";
    playAgainBtn.innerHTML = "Reset";
    gameButtons.style.visibility = "visible";
    menuButtons.style.visibility = "hidden";
    board.style.visibility = "visible";
    title.style.visibility = "hidden"
    homeBtn.style.visibility = "visible";
    sidebar.style.visibility = "visible";
    displayTxt.style.borderWidth = "0px";

    //set the grid of the board and the array
    setgrid();
    makeBoardArray();
    renderBoard();

    //set variables and restart the timer to 0:00
    restartTimer();
    firstClick = true;
    hasLost = false;
    hasWon = false;
    isPlaying = true;
    placedFlag = false;
    cheatActive = false;
}

function startTimer(){
    //get the start time
    startTime = Date.now() - timePassed;
    timer = setInterval(updateTimer, 1000); //update the timer every 1 second (1000ms)


}

function updateTimer(){
    //update the timer's time
    const currentTime = Date.now();

    timePassed = currentTime - startTime;

    //conver ms to minutes and seconds
    let minutes = Math.floor(timePassed/(1000*60));

    //converts ms to minutes
    let seconds = Math.floor((timePassed/1000) % 60);

    //converts seconds into a string to show the 0 in things like 1:07, rather than 1:7
    seconds = String(seconds).padStart(2, "0");

    timerTxt.innerHTML = minutes+":"+seconds;

}

function restartTimer(){
    //stop the timer and reset it
    clearInterval(timer);
    startTime = Date.now();
    timePassed = 0;
    timerTxt.innerHTML = "0:00";
}

function stopTimer(){
    //stops the timer from running
    clearInterval(timer);
    timer = null;
    timePassed = Date.now() - startTime;
}

function playMusic(){
    //play background music
    backgroundMusic.volume = 0.3;
    backgroundMusic.play();
}

function stopMusic(){
    //stop background music
    backgroundMusic.volume = 0.3;
    backgroundMusic.pause(); 
}

function diggingSound(num){
    //play a dig sound (different numbers have different sounds)
    let digSound;
    switch(true){
        case num==1:
            digSound = new Audio("soundEffetcs/dig1.mp3");
            digSound.play();
            break;

        case num==2:
            digSound = new Audio("soundEffetcs/dig2.mp3");
            digSound.play();
            break;

        case num==3:
            digSound = new Audio("soundEffetcs/dig3.mp3");
            digSound.play();
            break;

        case num==4:
            digSound = new Audio("soundEffetcs/dig4.mp3");
            digSound.play();
            break;

        case num==5:
            digSound = new Audio("soundEffetcs/dig5.mp3");
            digSound.play();
            break;

        case num==6:
            digSound = new Audio("soundEffetcs/dig6.mp3");
            digSound.play();
            break;

        case num==7:
            digSound = new Audio("soundEffetcs/dig7.mp3");
            digSound.play();
            break;

        case num==8:
            digSound = new Audio("soundEffetcs/dig8.mp3");
            digSound.play();
            break
        default:
            break;
    }
}

function flagSound(){
    //play the flag sound
    let flagSound = new Audio("soundEffetcs/flagSound.mp3");
    flagSound.play();
}

function bombSound(){
    //play the bomb sound
    let bombSound = new Audio("soundEffetcs/bomb.wav");
    bombSound.play();
}

function winSound(){
    //play the winning sound
    let winSound = new Audio("soundEffetcs/winSound.wav");
    winSound.volume = 0.3;
    winSound.play();
}

function clickSound(){
    //play the click sound (for buttons)
    let clickSound = new Audio("soundEffetcs/buttonClick.mp3");
    clickSound.play();
}

//checks how many bombs are around a given square
function findBombNumber(row, col){
    let bombs = 0
    for(i=-1; i<2; i++){ 
        for(j=-1; j<2; j++){
            //check that the surrounding square is not off of the board 
            if((row+i > -1 && row+i < gridHeight) && (col+j > -1 && col+j < gridLength)){
                let checkingSquare = boardArray[row+i][col+j];

                //if a square surrounding it is a bomb, count it
                if(checkingSquare == "bomb" || checkingSquare== "flagBomb"){
                    bombs++;
                }
            }
        }          
    }
    //return the amount of bombs next to it
    return bombs;
}

//when we have a new fully safe square (0 mines aroud) we will branch out until all squares have at least 1 mine surrounding them
//very important for the first click
function branchOut(){
  
    let runAgain = false //we may need to run this function within the function, this tells us if we have to or not
    for (let row = 0; row < gridHeight; row++) {
        for (let col = 0; col < gridLength; col++) {
        
            //find element at the row and coloumn
            let square = boardArray[row][col];

            if(square == "safe"){
                //check the  surrounding squares for bombs 
                let bombsNear = 0;
                let fullSafe = true; //this means it is surrounded by safe squares (for stopping infinite loops)

                for(i=-1; i<2; i++){ 
                    for(j=-1; j<2; j++){
                        //check that the surrounding square is not off of the board (in case they click an edge)
                        if((row+i > -1 && row+i < gridHeight) && (col+j > -1 && col+j < gridLength)){
                            
                            let checkingSquare = boardArray[row+i][col+j];
                            if(checkingSquare == "bomb" || checkingSquare == "flagBomb"){
                                bombsNear++;
                            }
                            if(checkingSquare == "empty"){
                                fullSafe = false;
                            }
                        }
                    }          
                }
              
                //if there are no bombs near, and it's not surrounded by safe squares already, make new safe squares
                if(bombsNear == 0 && !fullSafe){

                    //splice square with "safe square"
                    //make a safe square around the spot they clicked
                    for(i=-1; i<2; i++){ 
                        for(j=-1; j<2; j++){
                            //check that the surrounding square is not off of the board (in case they click an edge)
                            if((row+i > -1 && row+i < gridHeight) && (col+j > -1 && col+j < gridLength)){
                                
                                //splice square with "safe square"
                                if((boardArray[row+i][col+j]) !="flag"){ //don't break the flags if there is one
                                    boardArray[row+i].splice((col+j),1, "safe");
                                }
                            }
                        }          
                    }
                    runAgain = true;
                }
            }
        }
    }

    if(runAgain){ //if we discovered a new safe square, run branchOut() again
        branchOut();
    }
}

//create the board (depending on where they clicked)
function createBoard(x, y){ //x and y is the coordinates of the square they clicked

    let bombsAmount = bombsNeeded;

    //make a safe square around the spot they clicked
    for(i=-2; i<1; i++){ 
        for(j=-2; j<1; j++){
            //check that the surrounding square is not off of the board (in case they click an edge)
            if((y+i > -1 && y+i < gridHeight) && (x+j > -1 && x+j < gridLength)){
                //splice square with "safe square"
                boardArray[y+i].splice((x+j),1, "safe");
            }
        }          
    }

    let maxX = gridLength-1
    let maxY = gridHeight-1

    //add bombs
    while(bombsAmount>0){
        //get random x and y coordinates
        let randX = Math.floor(Math.random() * (maxX + 1))
        let randY = Math.floor(Math.random() * (maxY + 1))

        //add bomb if we found an empty square
        if(boardArray[randY][randX] == "empty"){
            boardArray[randY].splice((randX),1, "bomb");
            bombsAmount--
        }

    }
    //try to branch out after our click
    branchOut();
}

//renders board (replaces all board elements)
function renderBoard(){
    //reset the chip display (which is a grid display)
    let hasEmpty = false
    boardDisplay.innerHTML = "";

    let flagsDown = 0;

    //use nested for loop to make grid
    for (let row = 0; row < gridHeight; row++) {
        for (let col = 0; col < gridLength; col++) {
            //find element at the row and coloumn
            let square = boardArray[row][col];
            

            //make grid variables that have (0,0) at the bottom left and (8,8) at the top right
            let gridX = col+1;
            let gridY = gridHeight-row;


            //find the shade of the square we are on
            let shade = lightOrDark(gridX, gridY)
            let cellColor;


            //make basic cell/square
            const cell = document.createElement('div');
            cell.style.backgroundColor = cellColor;
            cell.id = "";
            cell.className = "cell"
            cell.style.width = cellWidth;
            cell.style.height = cellWidth;
            cell.style.maxWidth = cellWidth;
            cell.style.maxHeight = cellWidth;
            cell.style.gridColumn = gridX;
            cell.style.gridRow = gridY;
            
            //create bombnumber
            const bombNum = document.createElement("p");

            //use this to see if we have won
            if(square == "empty" || square == "flag"){
                hasEmpty = true;
            }

            //if we haven't cleard this square, or it's a bomb, set it to a green colar
            if(square == "empty" || square == "flag" || square == "flagBomb" || square == "bomb"){
                //find color
                if(shade =="light"){
                    cellColor = "5BBA6F";
                }
                else{
                    cellColor = "3FA34D";
                }
              
            }
            //if the square is safe
            else if(square == "safe"){
                //add number
                bombNum.className = "bombNumber";
                bombNum.style.fontSize = numberSize+"vw";

                bombNum.style.gridColumn = gridX;
                bombNum.style.gridRow = gridY;
                bombNum.innerHTML = findBombNumber(row, col);

                //if the number is greater than 4, check for an achivement
                if(findBombNumber(row,col)>4){
                    checkBombAchievements(findBombNumber(row,col));
                }

                //if it's a seven we will look for a six next to it for the sixSeven achivement
                if(findBombNumber(row, col) == 7 ){
                    checkForSixSeven(row, col);
                }

                //find color of safe square
                if(shade =="light"){
                    cellColor = "#e6c29f";
                }
                else{
                    cellColor = "#d7b799";
                }
            }
            
            
            if(hasLost || cheatActive){ //if we blew up, or have the cheat active, show bombs
                if( (boardArray[row][col])=="flagBomb" || (boardArray[row][col])=="bomb"){
                    const bombImg = document.createElement("img");
            
                    bombImg.className = "flag" //we use the same width and z-index of flags
                    bombImg.src = "bomb.png";

                    bombImg.style.width = (40/gridHeight)+"vw";
                    bombImg.style.height = (40/gridHeight)+"vw";
        
                    bombImg.style.gridColumn = gridX;
                    bombImg.style.gridRow = gridY;
                    boardDisplay.appendChild(bombImg);
                }
            }
            //if we haven't lost, check for and show flags
            if((boardArray[row][col])=="flag" || (!hasLost && !cheatActive && (boardArray[row][col])=="flagBomb") ){

                flagsDown++

                const flag = document.createElement("img");
        
                flag.className = "flag"
                flag.src = "flag.png";

                flag.style.width = (40/gridHeight)+"vw";
                flag.style.height = (40/gridHeight)+"vw";
    
                flag.style.gridColumn = gridX;
                flag.style.gridRow = gridY;
                boardDisplay.appendChild(flag);
            }

            //set color
            cell.style.backgroundColor = cellColor;
            //add the square to the display
            boardDisplay.appendChild(cell);

            //if the bomb number is 0, don't show it
            if(findBombNumber(row, col) != 0 ){
                //add the number to the display
                bombNum.style.color = getNumColor((findBombNumber(row, col)));
                cell.appendChild(bombNum);
            }
        }
    }  

    //set the text of the flags remaining at the top
    flagTxt.innerHTML = (bombsNeeded-flagsDown);

    if(hasEmpty == false){ //if this runs, they've cleared everything and have won
        stopTimer();
        displayTxt.innerHTML = "You Win!"
        displayTxt.style.borderWidth = "3px";
        playAgainBtn.innerHTML = "Play Again"
        winSound();
        checkWinningAchievements();
    }
} 

function checkWinningAchievements(){
    //checks all the modes for achivements, sets them to local storeage if achieved and does a pop up the , after a delay if needed
    //if they beat easy
    if(gameMode == "easy"){
        if(!hasApperenticeSweeper){
            localStorage.setItem("apperenticeSweeperKey", "true");

            popupDelay = popupsRunning * 3300;
            popupsRunning++;
            setTimeout(popup, popupDelay, "Apperentice Sweeper" , "Minesweeper Achievements/apperenticeSweeper.png");
        }

        //if they beat easy and did not place a flag
        if(!placedFlag){
            if(!hasPureLogic){
                localStorage.setItem("pureLogicKey", "true");

                popupDelay = popupsRunning * 3300;
                popupsRunning++;
                setTimeout(popup, popupDelay, "Pure Logic" , "Minesweeper Achievements/pureLogic.png");
            }
        }

        //if they beat easy in less than 10s
        if(timePassed<10000){
            if(!hasBeginnersLuck){
                localStorage.setItem("beginnersLuckKey", "true");

                popupDelay = popupsRunning * 3300;
                popupsRunning++;
                setTimeout(popup, popupDelay, "Beginners Luck" , "Minesweeper Achievements/beginnersLuck.png");
            }

        }
    }
    //if they beat medium
    else if(gameMode == "medium"){
        if(!hasIntermediateIntel){
            localStorage.setItem("InterMediateIntelKey", "true");
            console.log("setting II in storage")
            popupDelay = popupsRunning * 3300;
            popupsRunning++;
            setTimeout(popup, popupDelay, "Intermediate Intel" , "Minesweeper Achievements/IntermediateIntel.png");
        }
        //if they beat medium and did not place a flag
        if(!placedFlag){
            if(!hasUnmarkedTerritory){
                localStorage.setItem("unmarkedTerritoryKey", "true");

                popupDelay = popupsRunning * 3300;
                popupsRunning++;
                setTimeout(popup, popupDelay, "Unmarked Territory" , "Minesweeper Achievements/unmarkedTerritory.png");
            }
        }

        //if they beat medium in less than 2mins
        if(timePassed<120000){
            if(!hasRapidResponse){
                localStorage.setItem("rapidResponseKey", "true");

                popupDelay = popupsRunning * 3300;
                popupsRunning++;
                setTimeout(popup, popupDelay, "Rapid Response" , "Minesweeper Achievements/rapidResponse.png");
            }

        }
    }

    //if they beat hard
    else{
        if(!hasMasterDeminer){
            localStorage.setItem("masterDeminerKey", "true");

            popupDelay = popupsRunning * 3300;
            popupsRunning++;
            setTimeout(popup, popupDelay, "Master Deminer" , "Minesweeper Achievements/masterDeminer.png");
        }

        //if they beat hard and did not place a flag
        if(!placedFlag){
            if(!hasPhotographicMemory){
                localStorage.setItem("photographicMemoryKey", "true");

                popupDelay = popupsRunning * 3300;
                popupsRunning++;
                setTimeout(popup, popupDelay, "Photographic Memory" , "Minesweeper Achievements/photographicMemory.png");
            }
        }

        //if they beat hard in less than 5mins
        if(timePassed<300000){
            if(!hasMasterOfTime){
                localStorage.setItem("masterOfTimeKey", "true");

                popupDelay = popupsRunning * 3300;
                popupsRunning++;
                setTimeout(popup, popupDelay, "Master of Time" , "Minesweeper Achievements/masterOfTime.png");
            }
        }

        //if they did not place a flag and did it under 5 mins
        if(!placedFlag && timePassed<300000){
            if(!hasBombTechnician){
                localStorage.setItem("bombTechnicianKey", "true");

                popupDelay = popupsRunning * 3300;
                popupsRunning++;
                setTimeout(popup, popupDelay, "Bomb Technician" , "Minesweeper Achievements/bombTechnician.png");
            }
        }
    }

    //set achievements
    checkAchievementStorage();

}

function checkBombAchievements(num){
    //check for bomb achievements, do popup if nessasary, after a delay if needed
    switch(true){
        case num==5:
            if(!hasHighFive){
                localStorage.setItem("highFiveKey", "true");

                popupDelay = popupsRunning * 3300;
                popupsRunning++;
                setTimeout(popup, popupDelay, "High Five" , "Minesweeper Achievements/highFive.png");
            }
            break

        case num==6:
            if(!hasHexOfDanger){
                localStorage.setItem("hexOfDangerKey", "true");

                popupDelay = popupsRunning * 3300;
                popupsRunning++;

                setTimeout(popup, popupDelay, "HexOfDanger" , "Minesweeper Achievements/hexOfDanger.png");
            }
            break   

        case num==7:
            if(!hasLuckySeven){
                localStorage.setItem("luckySevenKey", "true");

                popupDelay = popupsRunning * 3300;
                popupsRunning++;
    
                setTimeout(popup, popupDelay, "Lucky Seven" , "Minesweeper Achievements/luckySeven.png");
            }
            break                 

        case num==8:
            if(!hasTotalIsolation){
                localStorage.setItem("totalIsolationnKey", "true");

                popupDelay = popupsRunning * 3300;
                popupsRunning++;
                setTimeout(popup, popupDelay, "Total Isolation" , "Minesweeper Achievements/totalIsolation.png");
            }
            break

        default:
            break;
    }

    //set achievements
    checkAchievementStorage();
}

//checks how many bombs are around a given square
function checkForSixSeven(row, col){
    let bombs = 0

    //check the surrounding square around the 7 for the safe square (make sure we've cleared it and find the direction)
    for(i=-1; i<2; i++){ 
        for(j=-1; j<2; j++){
            //check that the surrounding square is not off of the board 
            if((row+i > -1 && row+i < gridHeight) && (col+j > -1 && col+j < gridLength)){
                let checkingSquare = boardArray[row+i][col+j];
             

                //if we find a cleared square, check the squares around it and count the bombs
                if(checkingSquare == "safe"){
                    bombs = findBombNumber((row+i), (col+j));
       
                    //if we find exactly 6 bombs, give them the 67 achievement
                    if(bombs == 6){

                        //only do the popup if they haven't got it before
                        if(!hasSixSeven){
                            localStorage.setItem("sixSevenKey", "true");

                        
                            popupDelay = popupsRunning * 3300;
                            popupsRunning++;
                            setTimeout(popup, popupDelay, "6 7" , "Minesweeper Achievements/67.png");

                            //set achievement
                            checkAchievementStorage();


                        }
                    }

                }
            }
        }          
    }
}

//will find if the square is light or dark for when we display it (returns 'light' or 'dark');
function lightOrDark(x,y){
    let rowColor;
    let columnColor;
    let squareColor;
    
    //sees if the row position is black or white (uses the bottom row)
    if(x%2==0){
        rowColor = true; //means it's light
    }
    else{
        rowColor = false; //means it's dark
    }
    
    //sees if the column position is black or white (uses the left column)
    if(y%2==0){
        columnColor = true; //means it's light
    }
    else{
        columnColor = false; //means it's dark
    }
    
    //if the bottom row color and left column color are the same
    if(columnColor == rowColor){ 
        //the square is black
        squareColor = "dark";
    }
    //if the bottom row color and left column color are different
    else{
        //the square is white
        squareColor = "light";
    }
    return squareColor;
}

//function to highlight the hovered square
function highlightSquare(squareX, squareY){
 
    //find highlight element
    let highlight = document.getElementById("highlight");

    let squareSize = getBoardWidth()/gridLength //REPLACE WITH AMOUNT OF SQUARES LATER


    //position the highlight
    highlight.style.position = "absolute";
    highlight.style.width = squareSize+"px";
    highlight.style.height = squareSize+"px";

    highlight.style.top = ""+((gridHeight-squareY) * squareSize)+"px";

    //position the highlight different for the 3 modes
    if(gameMode == "easy"){
        highlight.style.left = ""+((((squareX-5) * squareSize) + (window.innerWidth)/5))+"px";
    }
    else if(gameMode == "medium"){
        highlight.style.left = ""+((((squareX-9) * squareSize) + (window.innerWidth)/5))+"px";
    }
    else{
        highlight.style.left = ""+((((squareX-6) * squareSize) + ((window.innerWidth)/100)*12.525))+"px";
    }
    
    //change highlight transparency
    highlight.style.opacity = "0.5"; 

    //store the square we are hovering over (for placing flags)
    highLightedX = squareX;
    highLightedY = squareY;
}

//takes in the mouse position (one dimension) and the board width, returns the square coordinate
function squareClicked(mouse, board, width){
    //equation to return the square coordinate
    let squareClicked = Math.ceil(mouse/(board/width));
    return squareClicked;
}

function setgrid(){
    //set the CSS of the board grid (how many rows cols)
    //also changes the width and margin left
    //depends on the mode (easy/medium/hard)
    if(gameMode == "easy"){
        board.style.width = "40vw";
        board.style.hieght = "40vw";
        board.style.transform = "translateX(75%)";

        boardDisplay.gridTemplateColumns = "repeat(8, 1fr);";
        boardDisplay.gridTemplateRows = "repeat(8, 1fr);";
    }
    else if(gameMode == "medium"){
        board.style.width = "40vw";
        board.style.hieght = "40vw";
        board.style.transform = "translateX(75%)";

        boardDisplay.gridTemplateColumns = "repeat(16, 1fr);";
        boardDisplay.gridTemplateRows = "repeat(16, 1fr);";
    }
    else{
        board.style.width = "75vw";
        board.style.hieght = "40vw";
        board.style.transform = "translateX(16.7%)";

        boardDisplay.gridTemplateColumns = "repeat(30, 1fr);";
        boardDisplay.gridTemplateRows = "repeat(16, 1fr);";

    }
}

function getBoardWidth(){ //return the board width in pxs
    let boardWidth;

    //if easy mode:
    if(gameMode == "easy"){
        boardWidth = 40*((window.innerWidth)/100);
    }
    else if(gameMode == "medium"){
        //medium
        boardWidth = 40*((window.innerWidth)/100);
    }
    else{ //for hard mode
        boardWidth = 75*((window.innerWidth)/100);
    }
    
    return boardWidth;

}

function getBoardHieght(){ //return board height
    return (40*((window.innerWidth)/100));
}

function makeBoardArray(){
    //makes the array for the board depending on the mode

    //reset the board array
    let row8 = [];
    boardArray = [];
 
    //depending on the mode, set the width of the grid (the amount of columns)
    if(gameMode == "easy"){
        row8 = ["empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty"];
    }
    else if(gameMode == "medium"){
        row8 = ["empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty"];
    }
    else{ //hard mode
     
        row8 = ["empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty"];
        
    }

    //add 7 more rows (regaurdless of mode)
    let row7 = row8.slice();
    let row6 = row8.slice();
    let row5 = row8.slice();
    let row4 = row8.slice();
    let row3 = row8.slice();
    let row2 = row8.slice();
    let row1 = row8.slice();

    //set board array
    boardArray = [row1, row2, row3, row4, row5, row6, row7, row8];

    if(gameMode != "easy"){ //for medium or hard (they have the same number of rows that we need to add)
        let row9 = row8.slice();
        let row10 = row8.slice();
        let row11 = row8.slice();
        let row12 = row8.slice();
        let row13 = row8.slice();
        let row14 = row8.slice();
        let row15 = row8.slice();
        let row16 = row8.slice();

        //set new board array
        boardArray = [row1, row2, row3, row4, row5, row6, row7, row8, row9, row10, row11, row12, row13, row14, row15, row16];
    }

}

function getNumColor(num){
    //take in the amount of bombs near a square, return the color of the number
    switch(true) {
        case num==1:
          return "#1e78cc";

        case num==2:
          return "#368b3b";

        case num==3:
            return "#d22a30";

        case num==4:
            return "#6e2193";
        
        case num==5:
            return "#f39d24";
        
        case num==6:
            return "#0096ac";
        
        case num==7:
            return "#5b5046";
        
        case num==8:
            return "#a29b93";
                
        default:
          return "black";
      }
}


function loadElements(){
    //load elements, we do it down here to not have a huge space taken up at the top

    //board
    board = document.getElementById("boardSpace");
    boardDisplay = document.getElementById("boardDisplay");

    //display elemtns
    title = document.getElementById("title");
    displayTxt = document.getElementById("displayText");

    //top UI
    sidebar = document.getElementById("sideBar");
    flagTxt = document.getElementById("remainingFlagsTxt");
    timerTxt = document.getElementById("timerTxt");

    //buttons
    menuButtons = document.getElementById("menuButtons");
    achievementsBtn = document.getElementById("achievementsBtn");
    achievementScreen = document.getElementById("achievementScreen");
    resetAchievementsBtn = document.getElementById("resetAchievementsBtn");
    easyBtn = document.getElementById("easyBtn");
    mediumBtn = document.getElementById("mediumBtn");
    hardBtn = document.getElementById("hardBtn");
    gameButtons = document.getElementById("gameButtons");
    playAgainBtn = document.getElementById("playAgainBtn");
    homeBtn = document.getElementById("homeBtn");
    musicBtn = document.getElementById("musicBtn");

    //popup elements
    popupContainer = document.getElementById("popup");
    popupImg = document.getElementById("popupImg");
    popupTxt = document.getElementById("popupTxt");


    //achievements
    displayAchievement = document.getElementById("displayAchievement");
    achievementsDescription = document.getElementById("achievementsDescription");
    achievementsTitle = document.getElementById("achievementsTitle");

    apperenticeSweeper = document.getElementById("apperenticeSweeper");
    hexOfDanger = document.getElementById("hexOfDanger");
    rapidResponse = document.getElementById("rapidResponse");
    photographicMemory = document.getElementById("photographicMemory");
    unmarkedTerritory = document.getElementById("unmarkedTerritory");
    IntermediateIntel = document.getElementById("IntermediateIntel");
    luckySeven= document.getElementById("luckySeven");
    masterOfTime = document.getElementById("masterOfTime");
    sixSeven = document.getElementById("67");
    masterDeminer = document.getElementById("masterDeminer");
    totalIsolation = document.getElementById("totalIsolation");
    pureLogic = document.getElementById("pureLogic");
    bombTechnician= document.getElementById("bombTechnician");
    highFive = document.getElementById("highFive");
    beginnersLuck = document.getElementById("beginnersLuck");
    questionMark = document.getElementById("questionMark");

    apperenticeSweeperImg = document.getElementById("apperenticeSweeperImg");
    hexOfDangerImg = document.getElementById("hexOfDangerImg");
    rapidResponseImg = document.getElementById("rapidResponseImg");
    photographicMemoryImg = document.getElementById("photographicMemoryImg");
    unmarkedTerritoryImg = document.getElementById("unmarkedTerritoryImg");
    IntermediateIntelImg = document.getElementById("IntermediateIntelImg");
    luckySevenImg = document.getElementById("luckySevenImg");
    masterOfTimeImg = document.getElementById("masterOfTimeImg");
    sixSevenImg = document.getElementById("67Img");
    masterDeminerImg = document.getElementById("masterDeminerImg");
    totalIsolationImg = document.getElementById("totalIsolationImg");
    pureLogicImg = document.getElementById("pureLogicImg");
    bombTechnicianImg = document.getElementById("bombTechnicianImg");
    highFiveImg = document.getElementById("highFiveImg");
    beginnersLuckImg = document.getElementById("beginnersLuckImg");
    questionMarkImg = document.getElementById("questionMarkImg");
}

function checkAchievementStorage(){
    //checks the local storage for data, set the data to variables if we have it
    if((localStorage.getItem("apperenticeSweeperKey") == "true" )){
        hasApperenticeSweeper = true;
        apperenticeSweeperImg.src = "Minesweeper Achievements/apperenticeSweeper.png";
    }
    if((localStorage.getItem("hexOfDangerKey") == "true" )){
        hasHexOfDanger = true;
        hexOfDangerImg.src = "Minesweeper Achievements/hexOfDanger.png";
    }
    if((localStorage.getItem("rapidResponseKey") == "true" )){
        hasRapidResponse = true;
        rapidResponseImg.src = "Minesweeper Achievements/rapidResponse.png";
    }
    if((localStorage.getItem("photographicMemoryKey") == "true" )){
        hasPhotographicMemory = true;
        photographicMemoryImg.src = "Minesweeper Achievements/photographicMemory.png";
    }
    if((localStorage.getItem("unmarkedTerritoryKey") == "true" )){
        hasUnmarkedTerritory = true;
        unmarkedTerritoryImg.src = "Minesweeper Achievements/unmarkedTerritory.png";
    }
    if((localStorage.getItem("InterMediateIntelKey") == "true" )){
        console.log("has II in storage")
        hasIntermediateIntel = true;
        IntermediateIntelImg.src = "Minesweeper Achievements/IntermediateIntel.png";
    }
    if((localStorage.getItem("luckySevenKey") == "true" )){
        hasLuckySeven = true;
        luckySevenImg.src = "Minesweeper Achievements/luckySeven.png";
    }
    if((localStorage.getItem("masterOfTimeKey") == "true" )){
        hasMasterOfTime = true;
        masterOfTimeImg.src = "Minesweeper Achievements/masterOfTime.png";
    }
    if((localStorage.getItem("sixSevenKey") == "true" )){
        hasSixSeven = true;
        sixSevenImg.src = "Minesweeper Achievements/67.png";
    }
    if((localStorage.getItem("masterDeminerKey") == "true" )){
        hasMasterDeminer = true;
        masterDeminerImg.src = "Minesweeper Achievements/masterDeminer.png";
    }
    if((localStorage.getItem("totalIsolationKey") == "true" )){
        hasTotalIsolation = true;
        totalIsolationImg.src = "Minesweeper Achievements/totalIsolation.png";
    }
    if((localStorage.getItem("pureLogicKey") == "true" )){
        hasPureLogic = true;
        pureLogicImg.src = "Minesweeper Achievements/pureLogic.png";
    }
    if((localStorage.getItem("bombTechnicianKey") == "true" )){
        hasBombTechnician = true;
        bombTechnicianImg.src = "Minesweeper Achievements/bombTechnician.png";
    }
    if((localStorage.getItem("highFiveKey") == "true" )){
        hasHighFive = true;
        highFiveImg.src = "Minesweeper Achievements/highFive.png";
    }
    if((localStorage.getItem("beginnersLuckKey") == "true" )){
        hasBeginnersLuck = true;
        beginnersLuckImg.src = "Minesweeper Achievements/beginnersLuck.png";
    }
    if((localStorage.getItem("questionMarkKey") == "true" )){
        hasQuestionMark = true;
        questionMarkImg.src = "Minesweeper Achievements/questionMark.png";
    }
   
}

function resetAchievements(){
    //reset all achievement booleans
    hasApperenticeSweeper = false;
    hasHexOfDanger = false;
    hasRapidResponse = false;
    hasPhotographicMemory = false;
    hasUnmarkedTerritory = false;
    hasIntermediateIntel = false;
    hasLuckySeven = false;
    hasMasterOfTime = false;
    hasSixSeven = false;
    hasMasterDeminer = false;
    hasTotalIsolation = false;
    hasPureLogic = false;
    hasBombTechnician = false;
    hasHighFive = false;
    hasBeginnersLuck = false;
    hasQuestionMark = false;

    //reset image paths
    apperenticeSweeperImg.src="Minesweeper Achievements/greyApperenticeSweeper.png";
    hexOfDangerImg.src="Minesweeper Achievements/greyHexOfDanger.png";
    rapidResponseImg.src="Minesweeper Achievements/greyRapidResponse.png";
    photographicMemoryImg.src="Minesweeper Achievements/greyPhotographicMemory.png";       
    IntermediateIntelImg.src="Minesweeper Achievements/greyIntermediateIntel.png";
    luckySevenImg.src="Minesweeper Achievements/greyLuckySeven.png";
    masterOfTimeImg.src="Minesweeper Achievements/greyMasterOfTime.png";
    sixSevenImg.src="Minesweeper Achievements/grey67.png";
    masterDeminerImg.src="Minesweeper Achievements/greyMasterDeminer.png";
    totalIsolationImg.src="Minesweeper Achievements/greyTotalIsolation.png";
    pureLogicImg.src="Minesweeper Achievements/greyPureLogic.png";
    bombTechnicianImg.src="Minesweeper Achievements/greyBombTechnician.png";
    highFiveImg.src="Minesweeper Achievements/greyHighFive.png";
    beginnersLuckImg.src="Minesweeper Achievements/greyBeginnersLuck.png";
    unmarkedTerritoryImg.src="Minesweeper Achievements/greyUnmarkedTerritory.png";
    questionMarkImg.src="Minesweeper Achievements/greyQuestionMark.png";
}
