var NUMBER_OF_COLS = 8,
    NUMBER_OF_ROWS = 8,
    BLOCK_HEIGHT = 50,
	BLOCK_WIDTH = 50;

var BLOCK_COLOUR_1 = '#F0F0F0',
    BLOCK_COLOUR_2 = '#E0E0E0',
    HIGHLIGHT_COLOUR = '#fb0006';

var MAX_X, MAX_Y;

//var ALL_LETTERS = ["অ", "আ", "ই", "ঈ", "উ", "ঊ", "ঋ", "এ", "ঐ", "ও", "ঔ", "ক", "খ", "গ", "ঘ", "ঙ", "চ", "ছ", "জ", "ঝ", "ঞ", "ট", "ঠ", "ড", "ঢ", "ণ", "ত", "থ", "দ", "ধ", "ন", "প", "ফ", "ব", "ভ", "ম", "য", "র", "ল", "শ", "ষ", "স", "হ", "ড়", "ঢ়", "য়", "ৎ", "ং", "ঃ", "ঁ", "ক্ষ", "ঙ্ক", "ঙ্গ", "জ্ঞ", "ঞ্চ", "ঞ্ছ", "ঞ্জ", "ত্ত", "ষ্ণ", "হ্ম", "ণ্ড"];

var ALL_LETTERS = ["অ", "আ", "ই", "ঈ", "উ", "ঊ", "ঋ", "এ", "ঐ", "ও", "ঔ", "ক", "খ", "গ", "ঘ", "ঙ", "চ", "ছ", "জ", "ঝ", "ঞ", "ট", "ঠ", "ড", "ঢ", "ণ", "ত", "থ", "দ", "ধ", "ন", "প", "ফ", "ব", "ভ", "ম", "য", "র", "ল", "শ", "ষ", "স", "হ", "ড়", "ঢ়", "য়", "ৎ", "ক্ষ", "ঙ্ক", "ঙ্গ", "জ্ঞ", "ঞ্চ", "ঞ্ছ", "ঞ্জ", "ত্ত", "ষ্ণ", "হ্ম", "ণ্ড"];

//var ALLOWED_CONJUNCTS = ["ক্ষ", "ঙ্ক", "ঙ্গ", "জ্ঞ", "ঞ্চ", "ঞ্ছ", "ঞ্জ", "ত্ত", "ষ্ণ", "হ্ম", "ণ্ড"];

var WORDS_LIST;// = ["ক ল ম", "কা গ জ", "ক্ষ মা", "পু তু ল", "স ম স্যা", "আ ম", "আ তা", "আ না র স", "জা ম", "ক লা", "লি চু", "কাঁ ঠা ল", "ক ম লা", "আ পে ল", "আ ঙ্গু র", "বে দা না", "জা ম রু ল", "জা ম্বু রা", "ক দ বে ল", "বে ল", "আ খ", "লে বু", "পে য়া রা", "না শ পা তি", "জ ল পা ই", "ব র ই"];
//var WORDS_LIST = ["আ তা", "জা ম", "জা ম রু ল", "জা ম্বু রা", "না শ পা তি"];
//var MODIFIED_WORDS_LIST;

var TIME_IN_SEC = 120;
var NUM_TO_PICK = 10;
var PICKED_WORDS_LIST;
var FOUND_WORDS_LIST;
var INSERTED_WORDS_LIST;

var RANDOM_LETTERS_LIST;
var ADD_TO_RANDOM_LETTERS;

var GRID;
var FILLED_GRID;

var IsTimeOut = false;

var COLOR = 'rgba('+ Math.floor((Math.random() * 256)) + ', ' + Math.floor((Math.random() * 256)) + ', ' + Math.floor((Math.random() * 256)) + ', 0.4)';

/*var BLOCK_COLOUR_1 = '#9f7119',
    BLOCK_COLOUR_2 = '#debf83',
    HIGHLIGHT_COLOUR = '#fb0006';*/
	
if(window.addEventListener) {
	window.addEventListener('load', function () {
		var canvas, tcanvas, context, tcontext;
		var isMouseDown;
        var touchX, touchY;
        var wordsData;

        //console.log(json);
        //var data = JSON.parse(json);
        loadData();

        setHeight();

        function loadJSON(callback) {   
            var xobj = new XMLHttpRequest();
                xobj.overrideMimeType("application/json");
            xobj.open('GET', 'data.json', true); // Replace 'my_data' with the path to your file
            xobj.onreadystatechange = function () {
                  if (xobj.readyState == 4 && xobj.status == "200") {
                    // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
                    callback(xobj.responseText);
                  }
            };
            xobj.send(null);  
         }

         function loadData(){
                loadJSON(function(response) {
              // Parse JSON string into object
                wordsData = JSON.parse(response);
                console.log(wordsData);
                loadAllWords();
                console.log(WORDS_LIST);
             });
         }

        document.querySelector("#homeLink").addEventListener ("click", function (event){
            clearInterval(intervalVar);
            document.querySelector("#timer").innerHTML = "সময়:";
            document.querySelector("#showScore").innerHTML = "স্কোর: 0";
            document.querySelector("#suggestion").innerHTML = "";

            loadAllWords();

            if(document.querySelector("#gameBoard").contains(document.querySelector("#tempCanvas"))){
        		document.querySelector("#gameBoard").removeChild(document.querySelector("#tempCanvas"));
        	}

            showPage("home");
        });

        document.querySelector("#homeLinkCat").addEventListener ("click", function (event){
            showPage("home");
        });

        document.querySelector("#homeLinkLast").addEventListener ("click", function (event){            
            document.querySelector("#timer").innerHTML = "সময়:";
            document.querySelector("#showScore").innerHTML = "স্কোর: 0";
            document.querySelector("#suggestion").innerHTML = "";

            loadAllWords();

            showPage("home");
        });

        document.querySelector("#startGame").addEventListener ("click", function (event){
            showPage("gameBoard");
            init();
        });

        document.querySelector("#category").addEventListener("click", function (event){
        	showPage("categories");
        });

        document.querySelector("#country").addEventListener("click", function (event){
        	//console.log(wordsData[0].countries)
            WORDS_LIST = wordsData[0].countries;
            document.querySelector("#startGame").click();
        });
        document.querySelector("#flower").addEventListener("click", function (event){
        	//alert("flower");
            WORDS_LIST = wordsData[0].flowers;
            document.querySelector("#startGame").click();
        });
        document.querySelector("#fruit").addEventListener("click", function (event){
        	//alert("fruit");
            WORDS_LIST = wordsData[0].fruits;
            document.querySelector("#startGame").click();
        });
        document.querySelector("#bird").addEventListener("click", function (event){
        	//alert("bird");
            WORDS_LIST = wordsData[0].birds;
            document.querySelector("#startGame").click();
        });
        document.querySelector("#fish").addEventListener("click", function (event){
        	//alert("fish");
            WORDS_LIST = wordsData[0].fishes;
            document.querySelector("#startGame").click();
        });
        document.querySelector("#other").addEventListener("click", function (event){
        	//alert("other");
            WORDS_LIST = wordsData[0].others;
            document.querySelector("#startGame").click();
        });

        document.querySelector("#instructions").addEventListener("click", function (event){
            alert("অনুভূমিক, উল্লম্ব বা কোনাকুনি বরাবর সোজা অথবা উল্টা শব্দ খুঁজে বের করুন।");
        });
        document.querySelector("#credits").addEventListener("click", function (event){
            alert("মাহফুজ");
        });
        document.querySelector("#tryAgain").addEventListener ("click", function (event){

            document.querySelector("#timer").innerHTML = "সময়:";
            document.querySelector("#showScore").innerHTML = "স্কোর: 0";

            if(document.querySelector("#gameBoard").contains(document.querySelector("#tempCanvas"))){
        		document.querySelector("#gameBoard").removeChild(document.querySelector("#tempCanvas"));
        	}

            showPage("categories");
            /*showPage("gameBoard");
            init();*/
        });
        function showHome(){
            showPage("home");
        }

		function init(){
			isMouseDown = false;
			// Find the canvas element.
			canvas = document.getElementById('wordsearch');
			FOUND_WORDS_LIST = new Array();
			INSERTED_WORDS_LIST = new Array();
			IsTimeOut = false;
			
			if (!canvas) {
				alert('Error: I cannot find the canvas element!');
				return;
			}

			if (!canvas.getContext) {
				alert('Error: no canvas.getContext!');
				return;
			}
			
            resizeCanvas();

			// Get the 2D canvas context.
			context = canvas.getContext('2d');
			if (!context) {
				alert('Error: failed to getContext!');
				return;
			}
			
			// Add the temporary canvas.
			var container = canvas.parentNode;
			tcanvas = document.createElement('canvas');
			if (!tcanvas) {
				alert('Error: I cannot create a new canvas element!');
				return;
			}

			tcanvas.id     = 'tempCanvas';
			tcanvas.width  = canvas.width;
			tcanvas.height = canvas.height;
			container.appendChild(tcanvas);

            document.querySelector("#tempCanvas").style.top = document.querySelector("#wordsearch").offsetTop+"px";
            document.querySelector("#tempCanvas").style.left = document.querySelector("#wordsearch").offsetLeft+"px";

            document.querySelector("#footer").style.left = (document.querySelector("#wordsearch").offsetLeft+5)+"px";

			tcontext = tcanvas.getContext('2d');
			
			// Attach the mousedown, mousemove and mouseup event listeners.

            var touchAvailable = ('createTouch' in document) || ('ontouchstart' in window);
            if(touchAvailable){
                tcanvas.addEventListener('touchstart', canvas_ts, false);
                tcanvas.addEventListener('touchmove', canvas_tm, false);
                tcanvas.addEventListener('touchend',   canvas_te, false);
            }
            else{
                tcanvas.addEventListener('mousedown', canvas_md, false);
                tcanvas.addEventListener('mousemove', canvas_mm, false);
                tcanvas.addEventListener('mouseup',   canvas_mu, false);
            }
			
			BLOCK_HEIGHT = canvas.height / NUMBER_OF_ROWS;
			BLOCK_WIDTH = canvas.width / NUMBER_OF_COLS;

			MAX_X = canvas.width;
			MAX_Y = canvas.height;
         
			// Draw the background
			drawBoard();

            initGrid();
			
			pickWords();

			drawLetters();

			document.getElementById("wordsLeft").innerHTML = "শব্দ বাকী: " + PICKED_WORDS_LIST.length;

			createTimer(TIME_IN_SEC);
		}

        function initGrid(){
            GRID = new Array(NUMBER_OF_COLS);
            for(var ii=0; ii<NUMBER_OF_COLS; ii++){
                GRID[ii] = new Array(NUMBER_OF_ROWS);
                for(var jj=0; jj<NUMBER_OF_ROWS; jj++){
                    GRID[ii][jj] = " ";
                }
            }
        }
		
		function pickWords(){
			PICKED_WORDS_LIST = new Array();
			for(var i=0; i<NUM_TO_PICK; i++){
				var word = WORDS_LIST[Math.floor((Math.random() * WORDS_LIST.length))];
				if(PICKED_WORDS_LIST.indexOf(word) > -1){
					i--;
				}
				else{
					PICKED_WORDS_LIST.push(word);
				}
			}
		}
		
		function updateCanvas () {
			context.drawImage(tcanvas, 0, 0);
			tcontext.clearRect(0, 0, tcanvas.width, tcanvas.height);
		}
		
		function getMidX(oX){
			var rX = oX;
			rX = parseInt(rX / BLOCK_WIDTH) * BLOCK_WIDTH + (BLOCK_WIDTH * 0.5);
			return rX;
		}
		
		function getMidY(oY){
			var rY = oY;
			rY = parseInt(rY / BLOCK_HEIGHT) * BLOCK_HEIGHT + (BLOCK_HEIGHT * 0.5);
			return rY;
		}

		function showPage(page){
			switch(page){
				case "home":
					document.querySelector("#home").style.display = "";
					document.querySelector("#categories").style.display = "none";
		            document.querySelector("#gameBoard").style.display = "none";
		            document.querySelector("#gameover").style.display = "none";
		            break;
				case "categories":
					document.querySelector("#home").style.display = "none";
					document.querySelector("#categories").style.display = "";
		            document.querySelector("#gameBoard").style.display = "none";
		            document.querySelector("#gameover").style.display = "none";
		            break;
				case "gameBoard":
					document.querySelector("#home").style.display = "none";
					document.querySelector("#categories").style.display = "none";
		            document.querySelector("#gameBoard").style.display = "";
		            document.querySelector("#gameover").style.display = "none";
		            break;
				case "gameover":
					document.querySelector("#home").style.display = "none";
					document.querySelector("#categories").style.display = "none";
		            document.querySelector("#gameBoard").style.display = "none";
		            document.querySelector("#gameover").style.display = "";
		            break;
		        default:
		        	break;
			}
		}

        function setHeight(){
            document.querySelector("#home").setAttribute("style", "height:"+window.innerHeight+"px");
            document.querySelector("#categories").setAttribute("style", "height:"+window.innerHeight+"px");
            document.querySelector("#gameBoard").setAttribute("style", "height:"+window.innerHeight+"px");
            document.querySelector("#gameover").setAttribute("style", "height:"+window.innerHeight+"px");
        }

        function loadAllWords(){
            WORDS_LIST = wordsData[0].flowers;
            WORDS_LIST = WORDS_LIST.concat(wordsData[0].fruits);
            WORDS_LIST = WORDS_LIST.concat(wordsData[0].birds);
            WORDS_LIST = WORDS_LIST.concat(wordsData[0].fishes);
            WORDS_LIST = WORDS_LIST.concat(wordsData[0].others);
        }
        function getTouchPos(e) {
            if (!e)
                var e = event;

            if (e.touches) {
                if (e.touches.length == 1) { // Only deal with one finger
                    var touch = e.touches[0]; // Get the information for finger #1
                    touchX=touch.pageX-touch.target.offsetLeft;
                    touchY=touch.pageY-touch.target.offsetTop;
                }
            }
        }

        function canvas_ts(ev){
            getTouchPos(ev);
            
            isMouseDown = true;

            ev._x = touchX;
            ev._y = touchY;
            x0 = ev._x;
            y0 = ev._y;
        }
        function canvas_tm(ev){
            getTouchPos(ev);

            if(!isMouseDown){
                return;
            }
            
            ev._x = touchX;
            ev._y = touchY;
            tcontext.clearRect(0, 0, tcanvas.width, tcanvas.height);

            tcontext.beginPath();
            tcontext.moveTo(getMidX(x0), getMidY(y0));
            tcontext.lineTo(getMidX(ev._x), getMidY(ev._y));
            
            tcontext.lineWidth = 20;
            tcontext.strokeStyle = COLOR;
            tcontext.lineCap = 'round';

            tcontext.stroke();
            tcontext.closePath();
        }
        function canvas_te(ev){
            getTouchPos(ev);
            if(isMouseDown){
                ev._x = touchX;
                ev._y = touchY;
                //canvas_tm(ev);
                isMouseDown = false;
                if(isValidPath(getMidX(x0), getMidY(y0), getMidX(ev._x), getMidY(ev._y)))
                {
                    var gotWord = getWord(getMidX(x0), getMidY(y0), getMidX(ev._x), getMidY(ev._y));
                    var spaceSeparatedWord = gotWord[0];
                    for(var i=1;i<gotWord.length;i++){
                        spaceSeparatedWord += (" " + gotWord[i]);
                    }
                    console.log('got: ' + spaceSeparatedWord);
                    if(INSERTED_WORDS_LIST.indexOf(spaceSeparatedWord) > -1 && FOUND_WORDS_LIST.indexOf(spaceSeparatedWord) == -1){
                        console.log('a word');
                        FOUND_WORDS_LIST.push(spaceSeparatedWord);
                        strikeFromSuggestion(spaceSeparatedWord);
                        document.getElementById("wordsLeft").innerHTML = "শব্দ বাকী: " + (INSERTED_WORDS_LIST.length - FOUND_WORDS_LIST.length);
                        var score = (FOUND_WORDS_LIST.length / INSERTED_WORDS_LIST.length) * 1000;
                        document.getElementById("showScore").innerHTML = "স্কোর: " + score;

                        if(INSERTED_WORDS_LIST.length == FOUND_WORDS_LIST.length){
                            //alert('Congrats!');
                            IsTimeOut = false;
                            finishGame(IsTimeOut);
                        }
                    }
                    else{
                        tcontext.clearRect(0, 0, tcanvas.width, tcanvas.height);
                        console.log('not a word');
                    }
                }
                else
                {
                    tcontext.clearRect(0, 0, tcanvas.width, tcanvas.height);
                }
                updateCanvas();
                COLOR = 'rgba('+ Math.floor((Math.random() * 256)) + ', ' + Math.floor((Math.random() * 256)) + ', ' + Math.floor((Math.random() * 256)) + ', 0.4)';
            }
        }
		
		function canvas_md(ev){
			isMouseDown = true;
            console.log(ev.pageX);
			if (ev.layerX || ev.layerX == 0) { // Firefox
				ev._x = ev.layerX;
				ev._y = ev.layerY;
			} else if (ev.offsetX || ev.offsetX == 0) { // Opera
				ev._x = ev.offsetX;
				ev._y = ev.offsetY;
			}
			x0 = ev._x;
			y0 = ev._y;
		}
		function canvas_mm(ev){
			if(!isMouseDown){
				return;
			}
			if (ev.layerX || ev.layerX == 0) { // Firefox
				ev._x = ev.layerX;
				ev._y = ev.layerY;
			} else if (ev.offsetX || ev.offsetX == 0) { // Opera
				ev._x = ev.offsetX;
				ev._y = ev.offsetY;
			}
			tcontext.clearRect(0, 0, tcanvas.width, tcanvas.height);

			tcontext.beginPath();
			tcontext.moveTo(getMidX(x0), getMidY(y0));
			tcontext.lineTo(getMidX(ev._x), getMidY(ev._y));
            
            tcontext.lineWidth = 20;
            tcontext.strokeStyle = COLOR;
            tcontext.lineCap = 'round';

			tcontext.stroke();
			tcontext.closePath();
		}
		function canvas_mu(ev){
			if(isMouseDown){
				if (ev.layerX || ev.layerX == 0) { // Firefox
					ev._x = ev.layerX;
					ev._y = ev.layerY;
				} else if (ev.offsetX || ev.offsetX == 0) { // Opera
					ev._x = ev.offsetX;
					ev._y = ev.offsetY;
				}
				canvas_mm(ev);
				isMouseDown = false;
                if(isValidPath(getMidX(x0), getMidY(y0), getMidX(ev._x), getMidY(ev._y)))
                {
                    var gotWord = getWord(getMidX(x0), getMidY(y0), getMidX(ev._x), getMidY(ev._y));
                    var spaceSeparatedWord = gotWord[0];
                    for(var i=1;i<gotWord.length;i++){
                        spaceSeparatedWord += (" " + gotWord[i]);
                    }
                    console.log('got: ' + spaceSeparatedWord);
                    if(INSERTED_WORDS_LIST.indexOf(spaceSeparatedWord) > -1 && FOUND_WORDS_LIST.indexOf(spaceSeparatedWord) == -1){
						console.log('a word');
						FOUND_WORDS_LIST.push(spaceSeparatedWord);
                        strikeFromSuggestion(spaceSeparatedWord);
						document.getElementById("wordsLeft").innerHTML = "শব্দ বাকী: " + (INSERTED_WORDS_LIST.length - FOUND_WORDS_LIST.length);
                        var score = (FOUND_WORDS_LIST.length / INSERTED_WORDS_LIST.length) * 1000;
                        document.getElementById("showScore").innerHTML = "স্কোর: " + score;

						if(INSERTED_WORDS_LIST.length == FOUND_WORDS_LIST.length){
							//alert('Congrats!');
							IsTimeOut = false;
                    		finishGame(IsTimeOut);
						}
                    }
                    else{
                        tcontext.clearRect(0, 0, tcanvas.width, tcanvas.height);
						console.log('not a word');
                    }
                }
                else
                {
                    tcontext.clearRect(0, 0, tcanvas.width, tcanvas.height);
                }
				updateCanvas();
                COLOR = 'rgba('+ Math.floor((Math.random() * 256)) + ', ' + Math.floor((Math.random() * 256)) + ', ' + Math.floor((Math.random() * 256)) + ', 0.4)';
			}
		}
        function isValidPath(x1, y1, x2, y2){
            if(x1 == x2){
                return true;
            }
            else if(y1 == y2){
                return true;
            }
            else{
                var dx = Math.abs(x1 - x2);
                var dy = Math.abs(y1 - y2);
                if(dx == dy){
                    return true;
                }
                return false;
            }
        }
        function getWord(x1, y1, x2, y2){
            var resWord = [];
            var tempX = -1;
            var tempY = -1;
            if(x1 == x2){
                if(y1 > y2){
                    tempY = y1;
                    y1 = y2;
                    y2 = tempY;
                }
                for(var i = y1; i <= y2 && i <= MAX_Y; i+=BLOCK_WIDTH){
                	console.log(i + ', ' + x1);
                    resWord.push(FILLED_GRID[parseInt(x1/BLOCK_HEIGHT)][parseInt(i/BLOCK_WIDTH)]);
                }
                if(tempY != -1){
                    resWord = flip(resWord);
                }
            }
            else if(y1 == y2){
                if(x1 > x2){
                    tempX = x1;
                    x1 = x2;
                    x2 = tempX;
                }
                for(var i = x1; i <= x2 && i <= MAX_X; i+=BLOCK_HEIGHT){
                	console.log(i + ', ' + y1);
                    resWord.push(FILLED_GRID[parseInt(i/BLOCK_HEIGHT)][parseInt(y1/BLOCK_WIDTH)])
                }
                if(tempX != -1){
                    resWord = flip(resWord);
                }
            }
            else{
                if(x2 > x1 && y2 > y1){
                    //top-left to bottom-right
                    for(var i=x1, j=y1; (i <= x2 && i <= MAX_X) && (j <= y2 && j <= MAX_Y); i+=BLOCK_HEIGHT, j+=BLOCK_WIDTH){
                        resWord.push(FILLED_GRID[parseInt(i/BLOCK_HEIGHT)][parseInt(j/BLOCK_WIDTH)]);
                    }
                }
                else if(x1 > x2 && y2 > y1){
                    //top-right to bottom-left
                    for(var i=x1, j=y1; (i >= x2 && i >= 0) && (j <= y2 && j <= MAX_Y); i-=BLOCK_HEIGHT, j+=BLOCK_WIDTH){
                        resWord.push(FILLED_GRID[parseInt(i/BLOCK_HEIGHT)][parseInt(j/BLOCK_WIDTH)]);
                    }
                }
                else if(x2 > x1 && y1 > y2){
                    //bottom-left to top-right
                    for(var i=x1, j=y1; (i <= x2 && i <= MAX_X) && (j >= y2 && j >= 0); i+=BLOCK_HEIGHT, j-=BLOCK_WIDTH){
                        resWord.push(FILLED_GRID[parseInt(i/BLOCK_HEIGHT)][parseInt(j/BLOCK_WIDTH)]);
                    }
                }
                else if(x1 > x2 && y1 > y2){
                    //bottom-right to top-left
                    for(var i=x1, j=y1; (i >= x2 && i >= 0) && (j >= y2 && j >= 0); i-=BLOCK_HEIGHT, j-=BLOCK_WIDTH){
                        resWord.push(FILLED_GRID[parseInt(i/BLOCK_HEIGHT)][parseInt(j/BLOCK_WIDTH)]);
                    }
                }
            }
            return resWord;
        }
        function strikeFromSuggestion(word){
            word = word.split(' ').join('');
            var suggestionList = document.querySelectorAll(".suggested")
            for(var i=0; i < suggestionList.length; i++)
            {
                if(word == suggestionList[i].innerHTML){
                    suggestionList[i].setAttribute("style", "color: red; text-decoration: line-through;");
                    /*console.log(suggestionList[i].parentNode);*/
                }
                //console.log(suggestionList[i].innerHTML);
            }
        }
        function addToSuggestion(word){
            //console.log(document.querySelector("#suggestion").innerHTML);
            if(document.querySelector("#suggestion").innerHTML == "")
            {
                document.querySelector("#suggestion").innerHTML = "<span class=\"suggested\">" + word.split(' ').join('') + "</span>";
            }
            else
            {
                document.querySelector("#suggestion").innerHTML =  document.querySelector("#suggestion").innerHTML + ", <span class=\"suggested\">" + word.split(' ').join('') + "</span>";
            }
        }
		function drawBoard()
		{   
			for(iRowCounter = 0; iRowCounter < NUMBER_OF_ROWS; iRowCounter++)
			{
				drawRow(iRowCounter);
			}   
			 
			// Draw outline
			context.lineWidth = 3;
			context.strokeRect(0, 0, NUMBER_OF_ROWS * BLOCK_HEIGHT, NUMBER_OF_COLS * BLOCK_WIDTH); 
		}

		function drawRow(iRowCounter)
		{
			// Draw 8 block left to right
			for(iBlockCounter = 0; iBlockCounter < NUMBER_OF_ROWS; iBlockCounter++)
			{
				drawBlock(iRowCounter, iBlockCounter);
			}
		}

		function drawBlock(iRowCounter, iBlockCounter)
		{   
			// Set the background
			context.fillStyle = getBlockColour(iRowCounter, iBlockCounter);
			 
			// Draw rectangle for the background
			context.fillRect(iRowCounter * BLOCK_HEIGHT, iBlockCounter * BLOCK_WIDTH, BLOCK_WIDTH, BLOCK_HEIGHT);
		 
			context.stroke();   
		}

		function getBlockColour(iRowCounter, iBlockCounter)
		{
			var cStartColour;
			 
			// Alternate the block colour
			if(iRowCounter % 2)
				cStartColour = (iBlockCounter % 2?BLOCK_COLOUR_1:BLOCK_COLOUR_2);
			else
				cStartColour = (iBlockCounter % 2?BLOCK_COLOUR_2:BLOCK_COLOUR_1);
				 
			return cStartColour;
		}


		function drawLetters()
		{
            for(var wordCounter=0; wordCounter < PICKED_WORDS_LIST.length; wordCounter++){
				console.log('adding: ' + PICKED_WORDS_LIST[wordCounter]);
                if(addWord(PICKED_WORDS_LIST[wordCounter], GRID)){
                    console.log('added');
                    INSERTED_WORDS_LIST.push(PICKED_WORDS_LIST[wordCounter]);
                    addToSuggestion(PICKED_WORDS_LIST[wordCounter]);
                }
                else
                {
                    console.log('not added');
                }
            }

            console.log('filled: ' + GRID);
            FILLED_GRID = fillBlanks(GRID);
            console.log('filled: ' + FILLED_GRID);

			for(iRowCounter = 0; iRowCounter < NUMBER_OF_ROWS; iRowCounter++)
			{
				for(iBlockCounter = 0; iBlockCounter < NUMBER_OF_ROWS; iBlockCounter++)
				{
					context.textAlign="center";
					context.fillStyle="#000000";
                    if(window.innerWidth <= 320){
                        context.font = "20px BenSenHandwriting";
                    }
                    else if(window.innerWidth > 320 && window.innerWidth <= 768){
                        context.font = "25px BenSenHandwriting";
                    }
                    else{
                        context.font = "30px BenSenHandwriting";
                    }
					
					context.fillText(FILLED_GRID[iRowCounter][iBlockCounter], iRowCounter * BLOCK_HEIGHT + BLOCK_HEIGHT/2, iBlockCounter * BLOCK_WIDTH + BLOCK_WIDTH/1.35);
				}
			}   
		}

        function fillBlanks(currentGrid){

            RANDOM_LETTERS_LIST = ALL_LETTERS.slice(0);
            for(var k=0;k<ADD_TO_RANDOM_LETTERS.length;k++){
                RANDOM_LETTERS_LIST.push(ADD_TO_RANDOM_LETTERS[k]);
            }

            var resultGrid = new Array(currentGrid.length);
            for(var i=0; i<currentGrid.length; i++){
                resultGrid[i] = new Array(currentGrid[i].length);
                for(var j=0; j<currentGrid[i].length; j++){
                    if(currentGrid[i][j] != " "){
                        resultGrid[i][j] = currentGrid[i][j];
                    }
                    else{
                        resultGrid[i][j] = RANDOM_LETTERS_LIST[Math.floor((Math.random() * RANDOM_LETTERS_LIST.length))];
                    }
                }
            }
            return resultGrid;
        }

        function flip(inn) {
            var res = new Array(inn.length);
            for(var i=inn.length-1, j=0; i>=0; i--, j++)
                res[j] = inn[i];
            return res;
        }
        
        function addWord(word, currentGrid){
            var prevGrid = new Array(currentGrid.length);
            for(var indC = 0; indC < currentGrid.length; indC++){
                prevGrid[indC] = new Array(currentGrid[indC].length);
                for(var indR = 0; indR < currentGrid[indC].length; indR++){
                    prevGrid[indC][indR] = currentGrid[indC][indR];
                }
            }

            var wordLetters = word.split(" ");
            ADD_TO_RANDOM_LETTERS = new Array();
            for(var k=0;k<wordLetters.length;k++){
                ADD_TO_RANDOM_LETTERS.push(wordLetters[k]);
            }

            for(var t = 0; t < 100; t++){
                var orientation = Math.floor((Math.random() * 2)); //0 or 1: 0 -> forward, 1 -> backword
                if(orientation == 1) wordLetters = flip(wordLetters);
                var direction   = Math.floor((Math.random() * 4)); // 0 = Horizontal, 1 = Vertical,  2 = Diagonal, 3 = Cross-Diagonal

                var row = Math.floor((Math.random() * (currentGrid.length - wordLetters.length + 1)));
                var col = Math.floor((Math.random() * (currentGrid[0].length - wordLetters.length + 1)));

				if(direction == 3) { row = row + wordLetters.length - 1; }

                var i=0;
                for(i=0; i<wordLetters.length; i++) {
                    if(currentGrid[row][col] == ' ' || currentGrid[row][col] == wordLetters[i]) {
                        currentGrid[row][col] = wordLetters[i];
                        
                        if(direction == 0) col++;
                        if(direction == 1) row++;
                        if(direction == 2) { col++; row++; }
						if(direction == 3) { col++; row--; }
                    } else {
                        for(var j=i; j>0; j--) {
                            if(direction == 0) col--;
                            if(direction == 1) row--;
                            if(direction == 2) { col--; row--; }
							if(direction == 3) { col--; row++; }
                            
                            currentGrid[row][col] = prevGrid[row][col]; 
                        }
                        break;
                    }
                }
                if(i == wordLetters.length) return true;
            }
            return false;
        }

        function finishGame(tout){

            var score = (FOUND_WORDS_LIST.length / INSERTED_WORDS_LIST.length) * 1000;

        	if(tout){
                document.querySelector("#gameoverHeader").innerHTML = "সময় শেষ!";
                document.querySelector("#score").innerHTML = score;
                document.querySelector("#tryAgain").innerHTML = "আবার চেষ্টা করবেন?";
                clearInterval(intervalVar); 
        	}
        	else{
                document.querySelector("#gameoverHeader").innerHTML = "অভিনন্দন!";
                document.querySelector("#score").innerHTML = score;
                document.querySelector("#tryAgain").innerHTML = "আবার খেলবেন?";
        		clearInterval(intervalVar);	
        	}
            showPage("gameover");
        	tcontext.clearRect(0, 0, tcanvas.width, tcanvas.height);
        	if(document.querySelector("#gameBoard").contains(document.querySelector("#tempCanvas"))){
        		document.querySelector("#gameBoard").removeChild(document.querySelector("#tempCanvas"));
        	}
            document.querySelector("#suggestion").innerHTML = "";
        }

        function resizeCanvas(){
            var param = window.innerWidth;
            if(window.innerWidth > window.innerHeight)
            {
                var param = window.innerHeight;
            }
            if(param <= 320)
            {
                document.querySelector("#wordsearch").setAttribute('width', '292' ); //max width
                document.querySelector("#wordsearch").setAttribute('height', '292' ); //max width

                document.querySelector("#footer").style.width = "288px";
                document.querySelector("#footer").style.fontSize = "16px";
                /*document.querySelector("#suggestion").style.height = "60px";*/
            }
            else if(param > 320 && param <= 360){
                document.querySelector("#wordsearch").setAttribute('width', '292' ); //max width
                document.querySelector("#wordsearch").setAttribute('height', '292' ); //max width

                document.querySelector("#footer").style.width = "288px";
                document.querySelector("#footer").style.fontSize = "16px";
                /*document.querySelector("#suggestion").style.height = "60px";*/
            }
            else if(param > 360 && param <= 480){
                document.querySelector("#wordsearch").setAttribute('width', '324' ); //max width
                document.querySelector("#wordsearch").setAttribute('height', '324' ); //max width

                document.querySelector("#footer").style.width = "320px";
                document.querySelector("#footer").style.fontSize = "17px";
                /*document.querySelector("#suggestion").style.height = "60px";*/
            }
            else if(param > 480 && param <= 768){
                document.querySelector("#wordsearch").setAttribute('width', '436' ); //max width
                document.querySelector("#wordsearch").setAttribute('height', '436' ); //max width

                document.querySelector("#footer").style.width = "432px";
                /*document.querySelector("#footer").style.fontSize = "25px";
                document.querySelector("#suggestion").style.height = "75px";*/
            }
            else if(param > 768 && param <= 800){
                document.querySelector("#wordsearch").setAttribute('width', '708' ); //max width
                document.querySelector("#wordsearch").setAttribute('height', '708' ); //max width

                document.querySelector("#footer").style.width = "704px";
                /*document.querySelector("#footer").style.fontSize = "25px";
                document.querySelector("#suggestion").style.height = "75px";*/
            }
            else if(param > 800 && param <= 980){
                document.querySelector("#wordsearch").setAttribute('width', '732' ); //max width
                document.querySelector("#wordsearch").setAttribute('height', '732' ); //max width

                document.querySelector("#footer").style.width = "728px";
                /*document.querySelector("#footer").style.fontSize = "25px";
                document.querySelector("#suggestion").style.height = "90px";*/
            }
            else{
                document.querySelector("#wordsearch").setAttribute('width', '900' ); //max width
                document.querySelector("#wordsearch").setAttribute('height', '900' ); //max width

                document.querySelector("#footer").style.width = "896px";
                /*document.querySelector("#footer").style.fontSize = "25px";
                document.querySelector("#suggestion").style.height = "90px";*/
            }
        }

        function createTimer(seconds) {
            intervalVar = setInterval(function () {
                if (seconds === 0) {
                    clearInterval(intervalVar);
                    IsTimeOut = true;
                    finishGame(IsTimeOut);
                    return;
                }
                var minutes = Math.floor(seconds / 60);
                var secondsToShow = (seconds - minutes * 60).toString();
                if (secondsToShow.length === 1) {
                    secondsToShow = "0" + secondsToShow; // if the number of seconds is '5' for example, make sure that it is shown as '05'
                }
                document.getElementById("timer").innerHTML = "সময়: " + minutes.toString() + ":" + secondsToShow;
                seconds--;
            }, 1000);
        }
        showHome();

	}, false);
}