$(function() {
    var position;
    var startingX,startingY ;
    var elem,wildcardelem;
    var placedTilesData;
    var Recentlyplacedtilesposition = new Array(); //array of tiles position
    var Recentlyplacedtiles = new Array(); //array of tiles position
    var draggingTilePreviousLocation;  //----present dragging tile's previous position
    var wildcardX,wildcardY;
    var wildcardLocation;
    var imageHeight,imageWidth;
    var minimumleft, maximumleft, minimumtop, maximumtop;
    var tilePlacedOnRackX = [], tilePlacedOnRackY = [], emptytilePlacesOnRackX = [];
    var draggablefunctioncalled = false;
    var tilesSelectedForSwapping = [];
    imageHeight = $(".img-thumbnail")[0].naturalWidth;
    imageWidth = $(".img-thumbnail")[0].naturalHeight;
    imageWidth= $( document ).width()-25;
    var dictionary_ = {};


var tilewidth = imageWidth/15;
    tilewidth += tilewidth * 0.05;
    minimumtop = -0.9929420 * tilewidth * 15;
    maximumtop = -1 * tilewidth;
    minimumleft = 0;
    maximumleft = 15 * tilewidth;


	
	
    $("#tile0").css({"left": tilewidth*1+"px","width": tilewidth*2+"px"});
    $("#tile1").css({"left": tilewidth*3+"px","width": tilewidth*2+"px"});
    $("#tile2").css({"left": tilewidth*5+"px","width": tilewidth*2+"px"});
    $("#tile3").css({"left": tilewidth*7+"px","width": tilewidth*2+"px"});
    $("#tile4").css({"left": tilewidth*9+"px","width": tilewidth*2+"px"});
    $("#tile5").css({"left": tilewidth*11+"px","width": tilewidth*2+"px"});
	$("#tile6").css({"left": tilewidth*13+"px","width": tilewidth*2+"px"});
    $("#imgResponsive").css({"margin-left": tilewidth*0.7+"px"});
    $("#letterTileContainer0").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
    $("#letterTileContainer1").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
    $("#letterTileContainer2").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
    $("#letterTileContainer3").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
    $("#letterTileContainer4").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
    $("#letterTileContainer5").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
    $("#letterTileContainer6").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
    $("#points0").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
    $("#points1").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
    $("#points2").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
    $("#points3").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
    $("#points4").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
    $("#points5").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
    $("#points6").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});

    tilePlacedOnRackX[0] = tilewidth*1;
    tilePlacedOnRackY[0] = 10;
    tilePlacedOnRackX[1] = tilewidth*3;
    tilePlacedOnRackY[1] = 10;
    tilePlacedOnRackX[2] = tilewidth*5;
    tilePlacedOnRackY[2] = 10;
    tilePlacedOnRackX[3] = tilewidth*7;
    tilePlacedOnRackY[3] = 10;
    tilePlacedOnRackX[4] = tilewidth*9;
    tilePlacedOnRackY[4] = 10;
    tilePlacedOnRackX[5] = tilewidth*11;
    tilePlacedOnRackY[5] = 10;
    tilePlacedOnRackX[6] = tilewidth*13;
    tilePlacedOnRackY[6] = 10;

    $("#wildcard_selector").css({"left": "0px","width": tilewidth*5+"px"});

    var scope_ = angular.element($("#mainElement")).scope();

    scope_.updateTileInformation(tilewidth);
        

    $( ".ui-draggable" ).on('mousedown', function(e) {
        draggablefunctioncalled = false;
   
        $( this ).addClass("held");

        var p = $(this);
        position = p.position();
        startingX = position.left;
        startingY = position.top;
        var tempx=startingX,tempy=startingY;


        draggingTilePreviousLocation= $(this).children('.index').text();

        elem = $(this);
        wildcardX= "";
        wildcardY= "";
        if($(elem).children('.tile').children('.points').text() == ''){
            wildcardelem =$(this);
            wildcardX = startingX;
            wildcardY = startingY;
        }



    });

    $( ".ui-draggable" ).on('mouseup', function(e) {
        $( this ).removeClass("held");
        var p = $(this);
        position = p.position();

    });

    $( ".ui-draggable" ).draggable({
        revert: false,
        start: function( event, ui ) {
            ui.helper.data('dropped', false);
        },
        stop: function(event, ui)
        {

            if(ui.helper.data('dropped') == false){

                $(elem).css({ "left": startingX+"px", "top": startingY+"px" });
            }

        }
    });

    $( ".ui-droppable" ).droppable({
        accept: '.ui-draggable',
        drop: function(event, ui){
            ui.draggable.data('dropped', true);
            $( this ).removeClass("held");
            var x = position.left;
            var y = position.top;

            $( ".tile" ).each(function() {
                var p = $( ".tile" );
                var position_ = p.position();
                if( x==position_.left && y==position_.top && $('.tile').length >7){
                    y=0;
                }
            });

            if( x > minimumleft && x < maximumleft && y > minimumtop && y < maximumtop){
                if(  x%tilewidth  < tilewidth/2 ){
                    if(x>=0){

                        x  =  x - (x%tilewidth) ;

                    }else{
                        var tilewidth_;
                        if(x<0) {
                            if (-1 * x % tilewidth > tilewidth / 2) {
                                x = x - (tilewidth + x % tilewidth);
                            } else {
                                x = x - (x % tilewidth);
                            }
                        }

                    }


                }else{
                    if(x>=0){
                        x  =  x + tilewidth - (x%tilewidth) ;
                    }else{
                        x  =  x - tilewidth - (x%tilewidth) ;
                    }


                }
                if(  -1 * y%tilewidth  < tilewidth/2 ){
                    y  =  y - (y%tilewidth) ;
                }else if( -1 * y%tilewidth  > tilewidth/2){
                    y  =  y - tilewidth - (y%tilewidth);
                }

                y-=tilewidth * 0.25;
                x+=tilewidth * 0.25;
                $(elem).css({ "top": y+"px", "left": x+"px", "width": tilewidth+"px" });
                $(elem).children( ".letterTileContainer_" ).css({ "font-size": tilewidth*0.73+"px","line-height": tilewidth*0.8284+"px" });
                $(elem).children( ".points" ).css({"font-size": tilewidth*0.48+"px","width": tilewidth*0.93+"px"});
                emptytilePlacesOnRackX.push(startingX);
            }else if(y >0 ){
                var diffbtwnPlacedTiels=-1000;
                var finalTilePlace,finalTilePlaceIndex;
                for(var i=0;i< emptytilePlacesOnRackX.length;i++){
                    if(diffbtwnPlacedTiels == -1000){
                        diffbtwnPlacedTiels = emptytilePlacesOnRackX[i] -x;
                        finalTilePlace = emptytilePlacesOnRackX[i];
                        finalTilePlaceIndex=i;
                    }
                    var tempdiffbtwnPlacedTiels = emptytilePlacesOnRackX[i] -x;

                    if(tempdiffbtwnPlacedTiels  < 0){
                        tempdiffbtwnPlacedTiels = -1*tempdiffbtwnPlacedTiels;
                    }

                    if(tempdiffbtwnPlacedTiels < diffbtwnPlacedTiels){
                        finalTilePlace = emptytilePlacesOnRackX[i];
                        finalTilePlaceIndex=i;
                        diffbtwnPlacedTiels = tempdiffbtwnPlacedTiels;

                    }

                }

                emptytilePlacesOnRackX.splice(finalTilePlaceIndex, 1);
                emptytilePlacesOnRackX.splice(emptytilePlacesOnRackX.indexOf(finalTilePlace), 1);

                if(finalTilePlace == undefined){
                    finalTilePlace = startingX;
                }

                $(elem).css({ "top": "10px", "left": finalTilePlace+"px", "width": tilewidth*2+"px" });
                $(elem).children( ".letterTileContainer_" ).css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
                $(elem).children( ".points" ).css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
            }else {
                $(elem).css({ "top": startingY+"px", "left": startingX+"px", "width": tilewidth*2+"px" });
                $(elem).children( ".letterTileContainer_" ).css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
                $(elem).children( ".points" ).css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});

            }






            x = x - minimumleft;
            y = -1 * ( y - maximumtop - maximumtop*0.25 );

            var cordx = x/tilewidth;
            var cordy = y/tilewidth;
            cordy = 14 - cordy;
            var tilePlace = (cordy) * 15 + cordx ;

            tilePlace = Math.round(tilePlace);

            if($(elem).children('.points').text() == ''){
                wildcardX = x;
                wildcardY = y;
                $("#wildcard_selector").show();
            }



            $(elem).children(".index").text(tilePlace);


            var alreadyExisted= false;

            var scope_ = angular.element($("#mainElement")).scope();
            var alreadyOnBoard =true;

            for(var indx=0; indx < scope_.tilePlacesArray.length;indx++){

                if($(elem).children(".index").text() == scope_.tilePlacesArray[indx]){

                    alreadyOnBoard = false;
                    break;
                }
            }

            if( $(elem).children(".index").text() <= 225 && !draggablefunctioncalled && alreadyOnBoard){

                for(var place=0; place<Recentlyplacedtilesposition.length;place++){
                    if(draggingTilePreviousLocation == Recentlyplacedtilesposition[place]){
                        if(tilePlace>225){
                            Recentlyplacedtiles.splice(place,1);
                            Recentlyplacedtilesposition.splice(place,1);
                            /* Recentlyplacedtiles[place] = "";
                             Recentlyplacedtilesposition[place] = "";*/
                        }else if(tilePlace == Recentlyplacedtilesposition[place]){
                            alreadyExisted= true;
                            break;
                        }else{
                            Recentlyplacedtilesposition[place] = tilePlace;
                            alreadyExisted= true;
                            break;
                        }
                    }

                }
                if(!alreadyExisted){
                    var indexVAlue = $(elem).children(".index").text();
                    for (var indx = 0; indx < Recentlyplacedtilesposition.length; indx++) {
                        if ( indexVAlue == Recentlyplacedtilesposition[indx]) {
                            alreadyOnBoard = false;
                            break;
                        }
                    }
                    if(alreadyOnBoard) {
                        wildcardLocation = place;
                        //alert('$(elem).children(".letterTileContainer_").text()'+$(elem).children(".letterTileContainer_").text().trim());
                        Recentlyplacedtiles.push($(elem).children(".letterTileContainer_").text().trim());
                        Recentlyplacedtilesposition.push(tilePlace);
                    }else{
                        if(startingY != 10){
                            temptilewidth=tilewidth;
                            $(elem).css({ "top": startingY+"px", "left": startingX+"px", "width": temptilewidth+"px" });
                            $(elem).children( ".letterTileContainer_" ).css({ "font-size": tilewidth*0.73+"px","line-height": tilewidth*0.8284+"px" });
                            $(elem).children( ".points" ).css({"font-size": tilewidth*0.48+"px","width": tilewidth*0.93+"px"});
                        }else{
                            temptilewidth = tilewidth*2;
                            $(elem).css({ "top": startingY+"px", "left": startingX+"px", "width": temptilewidth+"px" });
                            $(elem).children( ".letterTileContainer_" ).css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
                            $(elem).children( ".points" ).css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
                        }
                    }

                }

            }else if(!alreadyOnBoard) {
                if(startingY != 10){
                    temptilewidth=tilewidth;
                    $(elem).css({ "top": startingY+"px", "left": startingX+"px", "width": temptilewidth+"px" });
                    $(elem).children( ".letterTileContainer_" ).css({ "font-size": tilewidth*0.73+"px","line-height": tilewidth*0.8284+"px" });
                    $(elem).children( ".points" ).css({"font-size": tilewidth*0.48+"px","width": tilewidth*0.93+"px"});
                }else{
                    temptilewidth = tilewidth*2;
                    $(elem).css({ "top": startingY+"px", "left": startingX+"px", "width": temptilewidth+"px" });
                    $(elem).children( ".letterTileContainer_" ).css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
                    $(elem).children( ".points" ).css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
                }


            }
            draggablefunctioncalled = true;
            if(Recentlyplacedtilesposition.length <= 0){
                $('#recall_').hide();
                $('#swap_').show();
            }else{
                $('#swap_').hide();
                $('#recall_').show();
            }


        }

    });

    $(".wild_selector_tile").on('click',function(e){

        var tileId= $(wildcardelem).attr('id');
        tileId = tileId.replace('tile', '');
        var scope = angular.element($("#mainElement")).scope();
        scope.racklist[tileId] = $(this).children('.tile').children('.letter').text();
        scope.wildCardNewLetter = $(this).children('.tile').children('.letter').text();
        scope.updateRackNewLetter(tileId,$(this).children('.tile').children('.letter').text());
        scope.wildCardUsed = true;

        Recentlyplacedtiles[wildcardLocation]='-'+$(this).children('.tile').children('.letter').text();
        $("#wildcard_selector").hide();

    });

    $( ".play" ).on('click', function(e) {

        emptytilePlacesOnRackX = [];
        var scope = angular.element($("#mainElement")).scope();
        dictionary_ = scope.dictionary_();
        checkValidWordInDictionary(dictionary_,Recentlyplacedtiles);

        scope.play(Recentlyplacedtilesposition,Recentlyplacedtiles);
        returningTiles();

        $("#tile0").animate({top: '-=10px',left: '+=10px'}, {
            duration: 500,
            queue: false,
            complete: function() { $("#tile0").animate({top: '+=10px',left: '-=10px'}, {
                duration: 100,
                queue: false,
                complete: function () {
                    $("#tile1").animate({top: '-=10px', left: '+=10px'}, {
                        duration: 100,
                        queue: false,
                        complete: function () {
                            $("#tile1").animate({top: '+=10px', left: '-=10px'}, {
                                duration: 100,
                                queue: false,
                                complete: function () {
                                    $("#tile2").animate({top: '-=10px', left: '+=10px'}, {
                                        duration: 100,
                                        queue: false,
                                        complete: function () {
                                            $("#tile2").animate({top: '+=10px', left: '-=10px'}, {
                                                duration: 100,
                                                queue: false,
                                                complete: function () {
                                                    $("#tile3").animate({top: '-=10px', left: '+=10px'}, {
                                                        duration: 100,
                                                        queue: false,
                                                        complete: function () {
                                                            $("#tile3").animate({top: '+=10px', left: '-=10px'}, {
                                                                duration: 100,
                                                                queue: false,
                                                                complete: function () {
                                                                    $("#tile4").animate({top: '-=10px', left: '+=10px'}, {
                                                                        duration: 100,
                                                                        queue: false,
                                                                        complete: function () {
                                                                            $("#tile4").animate({top: '+=10px', left: '-=10px'}, {
                                                                                duration: 100,
                                                                                queue: false,
                                                                                complete: function () {
                                                                                    $("#tile5").animate({top: '-=10px', left: '+=10px'}, {
                                                                                        duration: 100,
                                                                                        queue: false,
                                                                                        complete: function () {
                                                                                            $("#tile5").animate({top: '+=10px', left: '-=10px'}, {
                                                                                                duration: 100,
                                                                                                queue: false,
                                                                                                complete: function () {
                                                                                                    $("#tile6").animate({top: '-=10px', left: '+=10px'}, {
                                                                                                        duration: 100,
                                                                                                        queue: false,
                                                                                                        complete: function () {
                                                                                                            $("#tile6").animate({top: '+=10px', left: '-=10px'}, {
                                                                                                                duration: 100,
                                                                                                                queue: false,
                                                                                                                complete: function () {}
                                                                                                            })
                                                                                                        }
                                                                                                    })
                                                                                                }
                                                                                            })
                                                                                        }
                                                                                    })
                                                                                }
                                                                            })
                                                                        }
                                                                    })
                                                                }
                                                            })
                                                        }
                                                    })
                                                }
                                            })
                                        }
                                    })
                                }
                            })
                        }
                    })
                }
            })}
        });

        $('#recall_').hide();
        $('#swap_').show();

    });


    $( ".resign" ).on('click', function(e) {

        emptytilePlacesOnRackX = [];
        	var scope = angular.element($("#mainElement")).scope();
        	scope.resign();
        $('#recall_').hide();
        $('#swap_').show();
        returningTiles();
        	});


    $( ".pass" ).on('click', function(e) {
        emptytilePlacesOnRackX = [];
        var scope = angular.element($("#mainElement")).scope();
        scope.passMyturn();
        $('#recall_').hide();
        $('#swap_').show();
        returningTiles();
    });

    $( ".recall" ).on('click', function(e) {
        emptytilePlacesOnRackX = [];
        var scope = angular.element($("#mainElement")).scope();

        scope.wildCardUsed = false;
        scope.shuffle();
        scope.changeSwapButton(false);
        $('#recall_').hide();
        $('#swap_').show();
        returningTiles();
    });
    $( ".poke" ).on('click', function(e) {
        	var scope = angular.element($("#mainElement")).scope();

            emptytilePlacesOnRackX = [];

        	scope.poke();
        $('#recall_').hide();
        $('#swap_').show();
            returningTiles();
        	});

    $( ".swapCancelling" ).on('click', function(e) {
        returningTiles();
    });

    $( ".swap_ok" ).on('click', function(e) {
        var scope = angular.element($("#mainElement")).scope();
        scope.putHideSwapPopup_();
        scope.swap(tilesSelectedForSwapping);
        returningTiles();
    });

    $( ".swapping" ).on('click', function(e) {
        returningTiles();
    });

    $(".tile").on('click', function(e){
        var scope = angular.element($("#mainElement")).scope();
        if(scope.showSwapPopup_() == true){
            var p = $(this);
            var position = p.position();
            $(this).css({"left": position.left+"px","top":"-100px"});
            tilesSelectedForSwapping.push($(this).children('.letter').text());
        }
    });

    $("#share_checkbox").on('click', function(e){
        $("#backmore").hide();
    });

        function returningTiles(){
            tilesSelectedForSwapping=[];
            $("#tile0").css({"left": tilewidth*1+"px","top":"10px","width": tilewidth*2+"px"});
            $("#tile1").css({"left": tilewidth*3+"px","top":"10px","width": tilewidth*2+"px"});
            $("#tile2").css({"left": tilewidth*5+"px","top":"10px","width": tilewidth*2+"px"});
            $("#tile3").css({"left": tilewidth*7+"px","top":"10px","width": tilewidth*2+"px"});
            $("#tile4").css({"left": tilewidth*9+"px","top":"10px","width": tilewidth*2+"px"});
            $("#tile5").css({"left": tilewidth*11+"px","top":"10px","width": tilewidth*2+"px"});
            $("#tile6").css({"left": tilewidth*13+"px","top":"10px","width": tilewidth*2+"px"});/*---------commented for height and width and left position-------------------------------------------------------*/
            $("#imgResponsive").css({"margin-left": tilewidth*0.7+"px"});
            $("#letterTileContainer0").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
            $("#letterTileContainer1").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
            $("#letterTileContainer2").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
            $("#letterTileContainer3").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
            $("#letterTileContainer4").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
            $("#letterTileContainer5").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
            $("#letterTileContainer6").css({"font-size": tilewidth*1.5+"px","line-height": tilewidth*1.7+"px"});
            $("#points0").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
            $("#points1").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
            $("#points2").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
            $("#points3").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
            $("#points4").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
            $("#points5").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
            $("#points6").css({"font-size": tilewidth*0.5+"px","width": tilewidth*1.8+"px"});
            Recentlyplacedtilesposition = new Array();
            Recentlyplacedtiles = new Array();
        }

        function checkValidWordInDictionary(dictionr, framedWord){

            var tempFrameWord =  "";
            for(var l=0;l<framedWord.length;l++){
                tempFrameWord +=framedWord[l];
            }

            var tempDict = dictionr.split(",");
            var countMatchings =0;

            for(var x=0;x<tempDict.length;x++){

                if(tempDict[x].length == tempFrameWord.length){

                    for(var y=0; y<tempDict[x].length;y++){

                        if(tempDict[x].search(framedWord[y]) != -1){
                            countMatchings++;
                        }else{
                            countMatchings = 0;
                        }

                    }
                }
                if(tempDict[x].length == countMatchings){
                    alert('word Matching');
                    break;
                }

            }

        }
});
