
Crafty.scene('GamePlay', function() {
    console.log("GAME PLAY SCREEN");
       
    if(soundDown == false){
        Crafty.audio.stop();
        Crafty.audio.play("GameMusic", -1)
    }
    
    init();
}); 


var mousex, mousey;
var mousexBtn, mouseyBtn;

// Mouse click and card's upper left corner offset
var xOff, yOff;

// Mouse offset between moves
var moveXAmount;
var moveYAmount;

// Card size
var cardHeight;
var cardWidth;
var cardInitVal;

// Canvas
var canvas
var ctx;
var tmpCanvas;
var tmpCtx;

// Is mouse down
var mouseDown;

// For cards
var activeCard;

var movingCardsDrawed;


// Deck types
var DeckType = {
    Foundation:1,
    Waste:2,
    Stock:3,
    Target:4
};

// Card lands
var CardLand = {
    Club:1,
    Diamond:2,
    Heart:3,
    Spade:4
};


// For decks
var deck1;
var deck2;
var deck3;
var deck4;
var deck5;
var deck6;
var deck7;
var stock;
var waste;
var target1;
var target2;
var target3;
var target4;


// Background
var background = new Image();
var cardBackground = new Image();
var deckBackground = new Image();
var btnBG = new Image();
var btnHoverBG = new Image();
var btnNGXPos;
var btnNGYPos;


// Loading graphics -message
var message;

// Window resize event
var resizeTimer;
var documentWidth;
var documentHeight;



function init() {

    // Mouse pos
    mousex=0; mousey=0;
    mousexBtn=0; mouseyBtn=0; 

    // Mouse click and card's upper left corner offset
    xOff=0; yOff=0;

    // Mouse offset between moves
    moveXAmount=0;
    moveYAmount=0;

    // Card size
    cardHeight=110;
    cardWidth=75;
    cardInitVal=0;

    // Canvas
    canvas
    ctx;
    tmpCanvas;
    tmpCtx;

    // Is mouse down
    mouseDown=false;

    // For cards
    activeCard=undefined;

    movingCardsDrawed  = true;


    // Deck types
    DeckType = {
        Foundation:1,
        Waste:2,
        Stock:3,
        Target:4
    };

    // Card lands
    CardLand = {
        Club:1,
        Diamond:2,
        Heart:3,
        Spade:4
    };


    // For decks
    deck1 = new DeckObject(DeckType.Foundation,0,0);
    deck2 = new DeckObject(DeckType.Foundation,0,0);
    deck3 = new DeckObject(DeckType.Foundation,0,0);
    deck4 = new DeckObject(DeckType.Foundation,0,0);
    deck5 = new DeckObject(DeckType.Foundation,0,0);
    deck6 = new DeckObject(DeckType.Foundation,0,0);
    deck7 = new DeckObject(DeckType.Foundation,0,0);
    stock = new DeckObject(DeckType.Stock,0,0);
    waste = new DeckObject(DeckType.Waste,0,0);
    target1 = new DeckObject(DeckType.Target,0,0);
    target2 = new DeckObject(DeckType.Target,0,0);
    target3 = new DeckObject(DeckType.Target,0,0);
    target4 = new DeckObject(DeckType.Target,0,0);
    


    // Background
    background = new Image();
    cardBackground = new Image();
    deckBackground = new Image();
    btnBG = new Image();
    btnHoverBG = new Image();
    btnNGXPos = 20;
    btnNGYPos = 394;
    

    // Loading graphics -message
    message;

    // Window resize event
    resizeTimer = undefined;
    documentWidth = 0;
    documentHeight = 0;
    

    // Document size
    deskCanvas = 2;

    document.getElementById("mainDiv").innerHTML = '<canvas id='+deskCanvasID+'></canvas>';

    documentWidth = document.body.offsetWidth;
    documentHeight = document.body.offsetHeight;

    // Card size
    cardHeight=documentWidth / 7;
    cardWidth=cardHeight / 1.46;

    canvas=document.getElementById(deskCanvasID);
    ctx=canvas.getContext("2d");
    canvas.width = documentWidth - canvas.offsetLeft*2;
    canvas.height = documentHeight - canvas.offsetTop;
    canvas.style.display="block";
   
    
    // Add the temporary canvas where main canvas is copied/drawed in mousedown
    // Temporary canvas is drawed in mousemove
    var container = canvas.parentNode;
    tmpCanvas = document.createElement('canvas');
    tmpCanvas.style.display="none";
    tmpCanvas.id     = 'tmpDeskCanvas';
    tmpCanvas.width  = canvas.width;
    tmpCanvas.height = canvas.height;
    tmpCanvas.offsetLeft = canvas.offsetLeft;
    tmpCanvas.offsetRight = canvas.offsetRight;
    container.appendChild(tmpCanvas);
    tmpCtx = tmpCanvas.getContext('2d');    
        
    // as Safari
    canvas.addEventListener( 'touchstart', ev_mousedown, false);
    canvas.addEventListener( 'touchmove', ev_mousemove, false);
    canvas.addEventListener( 'touchend', ev_mouseup, false );
    canvas.addEventListener('mouseup',   ev_mouseup, false);

    tmpCanvas.addEventListener( 'touchstart', ev_mousedown, false);
    tmpCanvas.addEventListener('touchmove', ev_mousemove, false);
    tmpCanvas.addEventListener('touchend',   ev_mouseup, false);
    tmpCanvas.addEventListener('mouseup',   ev_mouseup, false);

 // General graphics
    generalGraphicsLoadingIndex = 0;
    generalGraphicsArray.push('images/inGameBg.png');
    generalGraphicsArray.push('images/card_background.png');
    generalGraphicsArray.push('images/deck_background.png');
    generalGraphicsArray.push('images/pause_1.png');
    generalGraphicsArray.push('images/pause_2.png');
    
    
    // Card names
    cardLoadingIndex = 0;
    cardNameArray.push('images/Club_ace.png');
    cardNameArray.push('images/Club_2.png');
    cardNameArray.push('images/Club_3.png');
    cardNameArray.push('images/Club_4.png');
    cardNameArray.push('images/Club_5.png');
    cardNameArray.push('images/Club_6.png');
    cardNameArray.push('images/Club_7.png');
    cardNameArray.push('images/Club_8.png');
    cardNameArray.push('images/Club_9.png');
    cardNameArray.push('images/Club_10.png');
    cardNameArray.push('images/Club_jack.png');
    cardNameArray.push('images/Club_queen.png');
    cardNameArray.push('images/Club_king.png');
    cardNameArray.push('images/Diamond_ace.png');
    cardNameArray.push('images/Diamond_2.png');
    cardNameArray.push('images/Diamond_3.png');
    cardNameArray.push('images/Diamond_4.png');
    cardNameArray.push('images/Diamond_5.png');
    cardNameArray.push('images/Diamond_6.png');
    cardNameArray.push('images/Diamond_7.png');
    cardNameArray.push('images/Diamond_8.png');
    cardNameArray.push('images/Diamond_9.png');
    cardNameArray.push('images/Diamond_10.png');
    cardNameArray.push('images/Diamond_jack.png');
    cardNameArray.push('images/Diamond_queen.png');
    cardNameArray.push('images/Diamond_king.png');
    cardNameArray.push('images/Heart_ace.png');
    cardNameArray.push('images/Heart_2.png');
    cardNameArray.push('images/Heart_3.png');
    cardNameArray.push('images/Heart_4.png');
    cardNameArray.push('images/Heart_5.png');
    cardNameArray.push('images/Heart_6.png');
    cardNameArray.push('images/Heart_7.png');
    cardNameArray.push('images/Heart_8.png');
    cardNameArray.push('images/Heart_9.png');
    cardNameArray.push('images/Heart_10.png');
    cardNameArray.push('images/Heart_jack.png');
    cardNameArray.push('images/Heart_queen.png');
    cardNameArray.push('images/Heart_king.png');
    cardNameArray.push('images/Spade_ace.png');
    cardNameArray.push('images/Spade_2.png');
    cardNameArray.push('images/Spade_3.png');
    cardNameArray.push('images/Spade_4.png');
    cardNameArray.push('images/Spade_5.png');
    cardNameArray.push('images/Spade_6.png');
    cardNameArray.push('images/Spade_7.png');
    cardNameArray.push('images/Spade_8.png');
    cardNameArray.push('images/Spade_9.png');
    cardNameArray.push('images/Spade_10.png');
    cardNameArray.push('images/Spade_jack.png');
    cardNameArray.push('images/Spade_queen.png');
    cardNameArray.push('images/Spade_king.png');


   


    // Start loading general graphics
    initGeneralGraphics();

    
}

    
function winScreen(){
    $("#mainDiv").hide();
    Crafty.scene("GameMenu");
}
 
  
function pauseClicked(){
    console.log("pause Clicked");
    $("#mainDiv").hide();
     if(soundDown == false){
            Crafty.audio.stop();
            Crafty.audio.play("BgmMenu", -1)
        }
    createPauseScreen();

}





/******************************************************************************
 * requestAnimFrame
 * http://www.html5canvastutorials.com/labs/html5-canvas-ultimate-flash-killer/
 */ 
window.requestAnimFrame = (function(callback){
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){
        window.setTimeout(callback, 1000 / 60);
    };
})();

    
  
/******************************************************************************
 * Card object
 * http://www.javascriptkit.com/javatutors/object2.shtml
 */ 
function CardObject(id, x, y, img){
    // Properties
    this.id = id;
    this.land = 0;
    this.deckId = 0;
    this.isTurned = false;
    this.deckObject = undefined;
    this.x = x;
    this.y = y;
    this.oldX = x;
    this.oldY = y;
    this.img = img;
    this.topCard = undefined;
    this.isBlack = false;
    // Methods
    this.cancel = _CardObject_cancel;
    this.move = _CardObject_move;
    this.storePos = _CardObject_storePos;
    this.drawCard = _CardObject_drawCard;


}

function _CardObject_drawCard(ctx,drawAlsoTopCard) {
    // Draw this card
    if (this.isTurned) {
        ctx.drawImage(this.img,this.x,this.y,cardWidth,cardHeight);
    } else {
        ctx.drawImage(cardBackground,this.x,this.y,cardWidth,cardHeight);
    }
    // And also its top cards if needed
    if (drawAlsoTopCard && this.topCard) {
        this.topCard.drawCard(ctx,drawAlsoTopCard);
    }
}

function _CardObject_storePos(x,y) {
    this.x = x;
    this.y = y+10;
    this.oldX = x;
    this.oldY = y+10;


}

function _CardObject_move(x,y) {
    if (this.isTurned) {
        this.x = x;
        this.y = y;
        if (this.topCard) {
            this.topCard.move(x, y + cardHeight * 0.4);
        }
    }
}

function _CardObject_cancel() {
    this.x = this.oldX;
    this.y = this.oldY;
    if (this.topCard) {
        this.topCard.cancel();
    }
}


/******************************************************************************
 * Deck object
 */ 
function DeckObject(id, x, y){
    // Properties
    this.id = id;
    this.x = x;
    this.y = y;
    this.cardArray = new Array();
    // Methods
    this.setPos = _DeckObject_setPos;
    this.addCard = _DeckObject_addCard;
    this.cardUnderMouse = _DeckObject_cardUnderMouse;
    this.deckUnderMouse = _DeckObject_deckUnderMouse;
    this.drawDeck = _DeckObject_drawDeck;
    this.removeTopCard = _DeckObject_removeTopCard;
    this.removeFromThisCard = _DeckObject_removeFromThisCard;
}

function _DeckObject_drawDeck(ctx) {
    for(var i=0 ; i < this.cardArray.length ; i++) {
        var card = this.cardArray[i];
        // Do not draw active card and its top cards
        if (card!=activeCard) {
            card.drawCard(ctx,false);
        } else {
            return;
        }
    }
}

function _DeckObject_setPos(x,y){
    this.x = x;
    this.y = y;
}

function _DeckObject_addCard(card){
    var yCap = cardHeight * 0.4;
    // Set new position for the card
    if (this.id == DeckType.Foundation) {
        card.storePos(this.x,this.y + yCap * this.cardArray.length);
    } else {
        card.storePos(this.x,this.y);
    }
    // Store new deck data into card
    card.deckId = this.id; 
    card.deckObject = this;   
 
    // Set new card as top card of previous top
    if(this.cardArray.length > 0) {
        this.cardArray[this.cardArray.length-1].topCard = card;
    }
     // Add new card into deck array
    this.cardArray.push(card);
    
    // Add top card into this deck
    if (card.topCard) {
        this.addCard(card.topCard);
    }

     if(this.id == 4){
    console.log(" this.cardArray.length " +this.cardArray.length+ "winCheck :" +winCheck);
        
        if(this.cardArray.length == 13){
            winCheck = winCheck + 1;
      
        }// EO if condition for length

        if(winCheck == 4){
            winScreen();
            Crafty.scene("YouWon");
     
        }
    }// EO 
    console.log(" this.cardArray.length " +this.cardArray.length);

}

function _DeckObject_removeTopCard() {
    // Get top most card
    var card = this.cardArray.pop();
    
    // Reset old top card data
    if(this.cardArray.length > 0) {
        this.cardArray[this.cardArray.length-1].topCard = undefined;
        //this.cardArray[this.cardArray.length-1].isTurned = true;
    }
    return card;
}

function _DeckObject_removeFromThisCard(card) {
    // Remove all card from the deck starting from this card
    for(var i=0;i<this.cardArray.length;i++) {
        if (card != this.cardArray[this.cardArray.length-1]) {
            this.cardArray.pop();
            i--;
        } else if (card == this.cardArray[this.cardArray.length-1]) {
            this.cardArray.pop();
            if(this.cardArray.length > 0) {
                this.cardArray[this.cardArray.length-1].topCard = undefined;
                this.cardArray[this.cardArray.length-1].isTurned = true;
            }
            return;
        }
    }
}

function _DeckObject_cardUnderMouse(x,y){
    for(var i=this.cardArray.length-1;i>=0;i--) {
        var card = this.cardArray[i];
        if (card.x < x && card.y < y && card.x+cardWidth > x && card.y+cardHeight > y) {
            return card;
        }
    }
    return undefined;
}

function _DeckObject_deckUnderMouse(x,y) {
    var yCap = cardHeight * 0.4 * this.cardArray.length;
    if (this.id != DeckType.Foundation) {
        if (this.x < x && this.y < y && this.x+cardWidth > x && this.y+cardHeight > y) {
            return this;
        }
    } else {
        if (this.x < x && this.y < y && this.x+cardWidth > x && this.y+cardHeight+yCap > y) {
            return this;
        }
    }
    return undefined;
}


/******************************************************************************
 * Solitaire game logic
 * Check is the move allowed
 */ 
function isAllowedMove(fromDeck, toDeck, card) {
    // Get card that will be under this new card
    var topOfCard = undefined;
    if (toDeck.cardArray.length > 0)
        topOfCard = toDeck.cardArray[toDeck.cardArray.length-1];

    // Check deck issues        
    if (topOfCard && topOfCard.isTurned == false)
        return false;
    if (fromDeck.id != DeckType.Foundation && fromDeck.id != DeckType.Waste)
        return false;
    if (toDeck.id != DeckType.Foundation && toDeck.id != DeckType.Target)
        return false;
    
    // Card's decks must differ    
    if (fromDeck == toDeck)
        return false;

    // Check card's issues
    if(toDeck.cardArray.length>0) {
        if (toDeck.id == DeckType.Foundation) {
        // Card can be top of one step greater card and different color
        // Card can not be same color
        if (card.land == topOfCard.land || topOfCard.id != card.id + 1 || card.isBlack == topOfCard.isBlack)
            return false;
        } else if (toDeck.id == DeckType.Target) {
            // Cards must be in ascending order and same suite in 2 target deck
            if (topOfCard.id + 1 != card.id || topOfCard.land != card.land) 
                return false;
        }
    } else {
        // Moving top of empty deck
        // If there is no cards in the deck, then the first one must be King card in source decks 1
        if (toDeck.cardArray.length == 0 && card.id != 13 && toDeck.id == DeckType.Foundation)
            return false;

        // Ace card must be the first card in foundation
        if (toDeck.id == DeckType.Target && toDeck.cardArray.length == 0 && card.id != 1)
            return false;
    }
    
        
    return true;
}


/******************************************************************************
 * Clear canvas
 * TODO: Not in use
 */ 
function clearCanvas(x,y,w,h) {
    // Whole canvas
    ctx.clearRect(0,0,canvas.width,canvas.height);
}


/******************************************************************************
 * Window resize event handling
 */ 
function resizeEvent(event) {
    if(resizeTimer) {
        clearTimeout(resizeTimer);
        resizeTimer = undefined;
    }

}

function doResize() {
    resizeTimer = undefined;
    // TODO: is that good solution?
    window.location.reload();
}


/******************************************************************************
 * Draw fast single card
 * Draw only dirty background behind the card
 * Draw active moving card on top of all others
 */ 
function drawCardFast(cardToDraw, toContext, toBackground) {
    // Draw dirty background behind the card
    if (toBackground) {
        if (cardToDraw.topCard) {
        toContext.drawImage(toBackground, cardToDraw.x-moveXAmount, 0, cardWidth+moveXAmount*2, canvas.height, 
            cardToDraw.x-moveXAmount, 0, cardWidth+moveXAmount*2, canvas.height);
        } else {
        toContext.drawImage(toBackground, cardToDraw.x-moveXAmount, cardToDraw.y-moveYAmount, cardWidth+moveXAmount*2, cardHeight+moveYAmount*2, 
            cardToDraw.x-moveXAmount, cardToDraw.y-moveYAmount, cardWidth+moveXAmount*2, cardHeight+moveYAmount*2 );
        }
    }
    // Draw card and its parent cards
    cardToDraw.drawCard(toContext,true);
}

/******************************************************************************
 * Copy whole canvas and draw it once
 * Starts showing copy of the original canvas
 */ 
function copyCanvasAndDraw() {
    // Draw target canvas to ready for copying it
    ctx.drawImage(background,0,0,320,440);

    // Target backgrounds
    var capX = (canvas.width - (7 * cardWidth)) / 8; 
    ctx.drawImage(deckBackground,cardWidth*3+capX*4,capX+10,cardWidth,cardHeight);
    ctx.drawImage(deckBackground,cardWidth*4+capX*5,capX+10,cardWidth,cardHeight);
    ctx.drawImage(deckBackground,cardWidth*5+capX*6,capX+10,cardWidth,cardHeight);
    ctx.drawImage(deckBackground,cardWidth*6+capX*7,capX+10,cardWidth,cardHeight);

    ctx.drawImage(btnBG,btnNGXPos,btnNGYPos,30,26);
 
    // Draw decks
    deck1.drawDeck(ctx);
    deck2.drawDeck(ctx);
    deck3.drawDeck(ctx);
    deck4.drawDeck(ctx);
    deck5.drawDeck(ctx);
    deck6.drawDeck(ctx);
    deck7.drawDeck(ctx);
    stock.drawDeck(ctx);
    waste.drawDeck(ctx);
    target1.drawDeck(ctx);
    target2.drawDeck(ctx);
    target3.drawDeck(ctx);
    target4.drawDeck(ctx);
    

    // Draw target canvas to temporary canvas
    tmpCtx.drawImage(canvas, 0, 0);

    // And active card on that
    if (activeCard) {
        activeCard.drawCard(tmpCtx,true);
    }

    // Change temporary canvas to visible
    canvas.style.display="none";
    tmpCanvas.style.display="block";
}


/******************************************************************************
 * Set original canvas back to visible 
 */ 
function resetCanvas() {
    canvas.style.display="block";
    tmpCanvas.style.display="none";
}


/******************************************************************************
 * Draw all
 */ 
function drawAll() {
    // Background
   ctx.drawImage(background,0,0,320,440);

    // Target backgrounds
    var capX = (canvas.width - (7 * cardWidth)) / 8; 
    ctx.drawImage(deckBackground,cardWidth*3+capX*4,capX+10,cardWidth,cardHeight);
    ctx.drawImage(deckBackground,cardWidth*4+capX*5,capX+10,cardWidth,cardHeight);
    ctx.drawImage(deckBackground,cardWidth*5+capX*6,capX+10,cardWidth,cardHeight);
    ctx.drawImage(deckBackground,cardWidth*6+capX*7,capX+10,cardWidth,cardHeight);
    ctx.drawImage(deckBackground,cardWidth*0.3+capX*0.3,capX+10,cardWidth,cardHeight);
    
    ctx.drawImage(btnBG,btnNGXPos,btnNGYPos,30,26);

    // Draw decks
    deck1.drawDeck(ctx);
    deck2.drawDeck(ctx);
    deck3.drawDeck(ctx);
    deck4.drawDeck(ctx);
    deck5.drawDeck(ctx);
    deck6.drawDeck(ctx);
    deck7.drawDeck(ctx);
    stock.drawDeck(ctx);
    waste.drawDeck(ctx);
    target1.drawDeck(ctx);
    target2.drawDeck(ctx);
    target3.drawDeck(ctx);
    target4.drawDeck(ctx);

    // Draw active card lates to get it on top of all rest
    if (activeCard) {
        activeCard.drawCard(ctx,true);
    }
}


/******************************************************************************
 * Initialize general graphics
 */ 
function initGeneralGraphics() {
    if (generalGraphicsLoadingIndex==0) {
        background.onload  = function(){
            initGeneralGraphics();
        }; 
        background.src = generalGraphicsArray[generalGraphicsLoadingIndex];
        console.log('generalGraphicsLoadingIndex==0   '+generalGraphicsLoadingIndex);
    } else if (generalGraphicsLoadingIndex==1) {
        cardBackground.onload  = function(){
            initGeneralGraphics();
        }; 
        cardBackground.src = generalGraphicsArray[generalGraphicsLoadingIndex];
        console.log('generalGraphicsLoadingIndex==1   '+generalGraphicsLoadingIndex);
    } else if (generalGraphicsLoadingIndex==2) {
        deckBackground.onload  = function(){
            initGeneralGraphics();
        }; 
        deckBackground.src = generalGraphicsArray[generalGraphicsLoadingIndex];
        console.log('generalGraphicsLoadingIndex==2   '+generalGraphicsLoadingIndex);
    }else if (generalGraphicsLoadingIndex==3) {
        btnBG.onload = function(){
        initGeneralGraphics();
        }; 
        btnBG.src = generalGraphicsArray[generalGraphicsLoadingIndex];
        console.log('generalGraphicsLoadingIndex==3 '+generalGraphicsLoadingIndex);
        } 
        else if (generalGraphicsLoadingIndex==4) {
        btnHoverBG.onload = function(){
        initGeneralGraphics();
        }; 
        btnHoverBG.src = generalGraphicsArray[generalGraphicsLoadingIndex];
        console.log('generalGraphicsLoadingIndex==3 '+generalGraphicsLoadingIndex);
        } 
 
    else {
        initCards();
        
    }
    
    generalGraphicsLoadingIndex++;
    
}
    

/******************************************************************************
 * Initialize cards and load card graphics
 */ 
function initCards() {
//    updateMessage('Downloading graphics for cards... '+cardLoadingIndex+' / ' + cardNameArray.length); 


 if (cardNameArray.length == cardLoadingIndex) {
       // message.style.display='none';
        // All loaded
        initDecks();
        return;
    }

    // Create card object    
    var card = new CardObject(1,0,0,undefined);
    card.img = new Image();
    var landVal = (cardLoadingIndex+1) / 13;
  //  console.log('landVal = '+landVal);
    if (landVal<=1) {
        card.land = CardLand.Club;
        card.isBlack = true;
        if (cardInitVal > 12)
            cardInitVal = 0;
        cardInitVal++;
    } else if (landVal>1 && landVal<=2) {
        card.land = CardLand.Diamond;
        card.isBlack = false;
        if (cardInitVal > 12)
            cardInitVal = 0;
        cardInitVal++;
    } else if (landVal>2 && landVal<=3) {
        card.land = CardLand.Heart;
        card.isBlack = false;
        if (cardInitVal > 12)
            cardInitVal = 0;
        cardInitVal++;
    } else {
        card.land = CardLand.Spade;
        card.isBlack = true;
        if (cardInitVal > 12)
            cardInitVal = 0;
        cardInitVal++;
    }
    card.id = cardInitVal;
    card.img.onload = function(){
       if(cardLoadingIndex <= 52){
        initCards();
        }
        else{
        initDecks();
        }
        //setTimeout(initCards, 100);
    };
    card.img.src = cardNameArray[cardLoadingIndex];
   //     console.log('cardLoadingIndex = '+cardLoadingIndex);

    cardArray.push(card);
    cardLoadingIndex++; 
}


/******************************************************************************
 * Create all game decks
 */ 
function initDecks() {

    // Mess cards first
    for (var i=0;i<300;i++) {
        var randNro1=Math.floor(Math.random()*cardArray.length);
        var card1 = cardArray[randNro1];
        var randNro2=Math.floor(Math.random()*cardArray.length);
        var card2 = cardArray[randNro2];
        cardArray[randNro1] = card2;
        cardArray[randNro2] = card1;
    }
    
    // Deal cards into decks
    var capX = (canvas.width - (7 * cardWidth)) / 8; 
    var yPos = capX * 2 + cardHeight;
    var index = 0;

    deck1.setPos(capX,yPos);
    deck1.addCard(cardArray[index++]);
    deck1.cardArray[deck1.cardArray.length-1].isTurned = true;

    deck2.setPos(cardWidth*1+capX*2,yPos);
    deck2.addCard(cardArray[index++]);
    deck2.addCard(cardArray[index++]);
    deck2.cardArray[deck2.cardArray.length-1].isTurned = true;

    deck3.setPos(cardWidth*2+capX*3,yPos);
    deck3.addCard(cardArray[index++]);
    deck3.addCard(cardArray[index++]);
    deck3.addCard(cardArray[index++]);
    deck3.cardArray[deck3.cardArray.length-1].isTurned = true;

    deck4.setPos(cardWidth*3+capX*4,yPos);
    deck4.addCard(cardArray[index++]);
    deck4.addCard(cardArray[index++]);
    deck4.addCard(cardArray[index++]);
    deck4.addCard(cardArray[index++]);
    deck4.cardArray[deck4.cardArray.length-1].isTurned = true;

    deck5.setPos(cardWidth*4+capX*5,yPos);
    deck5.addCard(cardArray[index++]);
    deck5.addCard(cardArray[index++]);
    deck5.addCard(cardArray[index++]);
    deck5.addCard(cardArray[index++]);
    deck5.addCard(cardArray[index++]);
    deck5.cardArray[deck5.cardArray.length-1].isTurned = true;

    deck6.setPos(cardWidth*5+capX*6,yPos);
    deck6.addCard(cardArray[index++]);
    deck6.addCard(cardArray[index++]);
    deck6.addCard(cardArray[index++]);
    deck6.addCard(cardArray[index++]);
    deck6.addCard(cardArray[index++]);
    deck6.addCard(cardArray[index++]);
    deck6.cardArray[deck6.cardArray.length-1].isTurned = true;

    deck7.setPos(cardWidth*6+capX*7,yPos);
    deck7.addCard(cardArray[index++]);
    deck7.addCard(cardArray[index++]);
    deck7.addCard(cardArray[index++]);
    deck7.addCard(cardArray[index++]);
    deck7.addCard(cardArray[index++]);
    deck7.addCard(cardArray[index++]);
    deck7.addCard(cardArray[index++]);
    deck7.cardArray[deck7.cardArray.length-1].isTurned = true;

    stock.setPos(capX,capX);
    while (index < cardArray.length -1) {
        stock.addCard(cardArray[index++]);
    }
    waste.setPos(cardWidth*1+capX*2,capX);
    waste.addCard(cardArray[index++]);
    waste.cardArray[waste.cardArray.length-1].isTurned = true;
    
    target1.setPos(cardWidth*3+capX*4,capX);
    target2.setPos(cardWidth*4+capX*5,capX);
    target3.setPos(cardWidth*5+capX*6,capX);
    target4.setPos(cardWidth*6+capX*7,capX);
    
    // All created
    drawAll();
}


/******************************************************************************
 * Update message to the user
 */ 
function updateMessage(text) {
    message.innerHTML = text;
}


    
/******************************************************************************
 * Find card under mouse coordinates
 */ 
function cardUnderMouse(x,y) {
    // Find card under user mouse press
    var card = undefined;

    if(card = deck1.cardUnderMouse(x,y)) return card;
    if(card = deck2.cardUnderMouse(x,y)) return card;
    if(card = deck3.cardUnderMouse(x,y)) return card;
    if(card = deck4.cardUnderMouse(x,y)) return card;
    if(card = deck5.cardUnderMouse(x,y)) return card;
    if(card = deck6.cardUnderMouse(x,y)) return card;
    if(card = deck7.cardUnderMouse(x,y)) return card;
    if(card = waste.cardUnderMouse(x,y)) return card;
    if(card = stock.cardUnderMouse(x,y)) return card;

    return undefined;
}


/******************************************************************************
 * Find deck under mouse coordinates
 */ 
function deckUnderMouse(x,y) {
    // Find deck under user mouse press
    var deck = undefined;

    if(deck = deck1.deckUnderMouse(x,y)) return deck;
    if(deck = deck2.deckUnderMouse(x,y)) return deck;
    if(deck = deck3.deckUnderMouse(x,y)) return deck;
    if(deck = deck4.deckUnderMouse(x,y)) return deck;
    if(deck = deck5.deckUnderMouse(x,y)) return deck;
    if(deck = deck6.deckUnderMouse(x,y)) return deck;
    if(deck = deck7.deckUnderMouse(x,y)) return deck;
    if(deck = waste.deckUnderMouse(x,y)) return deck;
    if(deck = stock.deckUnderMouse(x,y)) return deck;
    if(deck = target1.deckUnderMouse(x,y)) return deck;
    if(deck = target2.deckUnderMouse(x,y)) return deck;
    if(deck = target3.deckUnderMouse(x,y)) return deck;
    if(deck = target4.deckUnderMouse(x,y)) return deck;


    
    return undefined;
}


/******************************************************************************
 * Mouse down
 */ 
function ev_mousedown (ev) {
    if (mouseDown)
        return;

    ev.preventDefault();
    console.log('mousedown  ev = '+ev);
    mouseDown = true;

    mousex = ev.targetTouches[0].pageX - canvas.offsetLeft;
    mousey = ev.targetTouches[0].pageY - canvas.offsetTop;

    if(((mousex >= 15) && (mousex <= 55)) && ((mousey >= 390 && mousey <= 425 ))){

        ctx.drawImage(btnHoverBG,btnNGXPos,btnNGYPos,30,26);
        console.log("mouse down on pause");
    }

    activeCard = cardUnderMouse(mousex,mousey);
    
    var activeDeck = deckUnderMouse(mousex,mousey);

    // User wants more cards from stock to waste
    if ((activeCard && activeCard.deckId == DeckType.Stock) || 
        (activeDeck && activeDeck.id == DeckType.Stock) ) {
        if (activeCard && stock.cardArray.length > 0) {
            console.log("mousedown on card");
            playSfxAudio("ButttonClick")
            // Do move from stock to waste
            stock.removeTopCard();
            activeCard.topCard = undefined;
            activeCard.isTurned = true;
            waste.addCard(activeCard);
        } else {
            // Stock is empty, copy card back from waste   playSfxAudio("ButttonClick")
            var card = waste.removeTopCard();
            while(card) {
                card.topCard = undefined;
                card.isTurned = false;
                stock.addCard(card);
                card = waste.removeTopCard();
            }
        }
        mouseDown = false;
        activeCard = undefined;
        return;
    }

    // User starts moving cards
    if (activeCard) {
        console.log("mousedown 2 on card");
        playSfxAudio("ButttonClick")
        xOff = mousex - activeCard.x;
        yOff = mousey - activeCard.y;
        
        // Copy main canvas and start drawing copy of it
        copyCanvasAndDraw();
    }
    else {
        mouseDown = false;
    }    

}



/******************************************************************************
 * Mouse move
 */ 
function ev_mousemove (ev) {
    if (!mouseDown)
        return;

    if (!activeCard) {
        return;
    }
    console.log('mousemove  ev = '+ev);

    ev.preventDefault();

    var newX = ev.targetTouches[0].pageX - tmpCanvas.offsetLeft;
    var newY = ev.targetTouches[0].pageY - tmpCanvas.offsetTop;

    console.log("newX : "+newX+ " newY :" +newY);

    // Is mouse position outside of canvas?
    var tmpX = newX - xOff;
    var tmpY = newY - yOff;
    if (tmpX < 1 || 
        tmpX + cardWidth >= canvas.width ||
        tmpY < 1) {
        // MouseUp
        mouseDown = false;
        // Cancel move
        activeCard.cancel();
        activeCard = undefined;
        // Draw whole main canvas
        drawAll();
        // Start showing again main canvas
        resetCanvas();
        return;
    }

    // Move card
    if (movingCardsDrawed) {
+        console.log("card moved");
        moveXAmount = Math.abs(mousex - newX) +2;
        moveYAmount = Math.abs(mousey - newY) +2;
        movingCardsDrawed = false;
    } else {
        console.log("card moved else");
        moveXAmount += Math.abs(mousex - newX) +2;
        moveYAmount += Math.abs(mousey - newY) +2;
    }
    
    mousex = newX;
    mousey = newY;
    activeCard.move(mousex - xOff, mousey - yOff);
    
    // request new frame
    requestAnimFrame(function(){
        drawCardFast(activeCard,tmpCtx,canvas);
        movingCardsDrawed = true;
    });
 
}


/******************************************************************************
 * Mouse up
 */ 
function ev_mouseup (ev) {
    mouseDown = false;

    ev.preventDefault();

    var x = mousex;
    var y = mousey;
    
    
    
    console.log('mouseUp  ev = '+ev.targetTouches.length);
    
    
    if (ev.targetTouches.length > 0) {
        //playSfxAudio("ButttonClick")
        console.log('mouseUp 1');
        x = ev.targetTouches[0].pageX - tmpCanvas.offsetLeft;
        y = ev.targetTouches[0].pageY - tmpCanvas.offsetTop;
    }

    // Change card into different deck
    if (activeCard) {
        console.log('mouseUp 2');
        //playSfxAudio("ButttonClick")
        var activeDeck = deckUnderMouse(x,y);
        if (activeDeck) {
            if (isAllowedMove(activeCard.deckObject, activeDeck, activeCard)) {
                
                // Remove cards from the original deck
                activeCard.deckObject.removeFromThisCard(activeCard);
                // Add cards into new deck
                activeDeck.addCard(activeCard);
            }
            else {
                activeCard.cancel();
            }
        }
        else {
            activeCard.cancel();
        }
    }

    activeCard = undefined;

    // Draw whole main canvas
    drawAll();
    // Start showing again main canvas
    resetCanvas();

    movingCardsDrawed = true;

    mousexBtn = ev.changedTouches[0].pageX;
    mouseyBtn = ev.changedTouches[0].pageY;


    if(((mousexBtn >= 15) && (mousexBtn <= 55)) && ((mouseyBtn >= 420 && mouseyBtn <= 460 ))){

        pauseClicked();
    } 

}

   