﻿var itemCnt = 0;
var gridRows = 0;
var gridCols = 5;
var boxHeight = 106;
var boxWidth = 197;
var gridArray;
var posLock = false;
var rndNumCol;
var rndNumRow;
var largeCnt = 0;
var medCnt = 0;
var smallCnt = 0;
var smallRowNum = 0;
var smallColNum = 0;
var totalGridPlaces = 0;

function bindDocs() {
    var timer;
    var pieceStats = '';
    var touchOS = ('ontouchstart' in document.documentElement) ? true : false;

    itemCnt = 0;
    gridRows = 0;
    gridCols = 5;
    boxHeight = 106;
    boxWidth = 197;
    gridArray;
    posLock = false;
    rndNumCol;
    rndNumRow;
    largeCnt = 0;
    medCnt = 0;
    smallCnt = 0;
    smallRowNum = 0;
    smallColNum = 0;
    totalGridPlaces = 0;

    // Set the size counts.
    itemCnt = $('.hidCount').text();
    largeCnt = $('.hidLargeCount').text();
    medCnt = $('.hidMedCount').text();
    smallCnt = $('.hidSmallCount').text();

    totalGridPlaces = (largeCnt * 4) + (medCnt * 2) + (smallCnt * 1);

    // sets the rows needed to display all the items.
    gridRows = Math.ceil((totalGridPlaces + 3) / 5);

    // set the pages size.  The Grid Pieces css are positioned absolute so they do not force a height on the page.  This adjusts the div.DocumentGrid class.
    // The additon of 80 is to add padding to the bottom of the page.
    $('.DocumentGrid').css('height', ((gridRows * boxHeight) + 80) + "px");

    // Sets up the array to store all the grid piece positions in.
    buildGridArray();


    $('.GridPiece').each(function (e) {
        pieceStats = $(this).find('input').attr('value').split('--');
        var pieceSize = pieceStats[1];
        var pieceID = pieceStats[0];
        
        // moves all the pieces around the grid and check if right most item
        var isRightMostItem = buildGrid(pieceSize, pieceID, this);

        if (pieceSize == 'Small') {
            var text = $(this).find('.GridPieceTeaserText');
            var back = $(this).find('.GridPieceTeaserBack');
            text.css('height', '80px');
            back.css('height', '97px');
        }

        if (touchOS)
            setupItemForClick(this, pieceSize, pieceID, isRightMostItem);
        else
            setupItemForMouseover(this, pieceSize, pieceID, isRightMostItem, timer);        
    });
    animateIn();
}


function buildGridArray() {

    gridArray = new Array(gridCols);

    for (i = 0; i < gridRows; i++) {
        gridArray[i] = new Array(gridCols)
    }

    //set the first three positions as closed for the page text.
    gridArray[0][0] = "C";
    gridArray[0][1] = "C";
    gridArray[0][2] = "C";

}


function buildGrid(pieceSize, pieceID, gridPiece) {

    var buildCounter = 0;
    //find position
    rndNumCol = 2;
    rndNumRow = 0;

    while (!posLock) {
        switch (pieceSize) {
            case 'large':
                rndNumCol = Math.floor(Math.random() * (gridCols - 1));
                rndNumRow = Math.floor(Math.random() * (gridRows - 1));
                break;
            case 'Med':
                rndNumCol = Math.floor(Math.random() * gridCols);
                rndNumRow = Math.floor(Math.random() * (gridRows - 1));
                break;
            default:
                if (rndNumCol >= gridCols - 1) {
                    rndNumCol = 0;
                    rndNumRow++;
                }
                else
                    rndNumCol++;
                break;
        }

        // check is position is open;
        var posLock = Boolean(checkPosition(pieceSize, pieceID));

        // close position
        if (posLock) {
            closePosition(pieceSize);
        }

        buildCounter++;
        if (buildCounter == (gridRows * gridCols)) {
            // add row  
            gridRows++;
            gridArray[gridRows - 1] = new Array(gridCols)
            $('.DocumentGrid').css('height', ((gridRows * boxHeight) + 80) + "px");
            buildCounter = 0;
        }
    }
    
    //set piece position on the Grid.
    setPiecePosition(gridPiece);
    posLock = false;

    //retrun true if it is right most item
    return (rndNumCol == 4 && (pieceSize == 'Med' || pieceSize == 'Small')) || (rndNumCol == 3 && pieceSize == 'large');
}



function checkPosition(pieceSize, pieceID) {
    var bolOpen = false;

    if (gridArray[rndNumRow][rndNumCol] == undefined) {
        bolOpen = true;

        // check for the larger items to make sure the other grid spots are open to place it.
        switch (pieceSize) {
            case 'large':
                if (rndNumRow < gridRows - 2) {
                    for (var col = 0; col < 2; col++) {
                        for (row = 0; row < 2; row++) {
                            if (gridArray[rndNumRow + row][rndNumCol + col] == "C") {
                                bolOpen = false;
                                break;
                            }
                        }
                    }

                }
                else
                    bolOpen = false;
                break;
            case 'Med':
                if (gridArray[rndNumRow + 1][rndNumCol] == "C") {
                    bolOpen = false;
                }
                break;
            default:
                break;
        }

        return bolOpen;
    }
}


function closePosition(pieceSize) {
    // set this position as closed.  This is a large piece so we need to close 4 spots
    switch (pieceSize) {
        case 'large':
            gridArray[rndNumRow][rndNumCol] = "C";
            gridArray[rndNumRow][rndNumCol + 1] = "C";
            gridArray[rndNumRow + 1][rndNumCol] = "C";
            gridArray[rndNumRow + 1][rndNumCol + 1] = "C";
            break;
        case 'Med':
            gridArray[rndNumRow][rndNumCol] = "C";
            gridArray[rndNumRow + 1][rndNumCol] = "C";
            break;
        default:
            gridArray[rndNumRow][rndNumCol] = "C";
            break;
    }
}


function setPiecePosition(gridPiece) {
    $(gridPiece).css('left', (rndNumCol * boxWidth) + 'px');
    $(gridPiece).css('top', (rndNumRow * boxHeight) + 'px');

}


function animateIn() {
    var intCnt = 0;

    var intNum = setInterval(function () {
        if (intCnt < itemCnt) {
            $("#GP" + intCnt).fadeIn('slow');
            intCnt++
        }
        else {
            clearInterval(intNum);
        }
    }, 200);
    
}



function setupItemForMouseover(item, pieceSize, pieceID, isRightMostItem, timer) {
    //set the mouseover/click states of the grid pieces.
    $(item).mouseenter(function (e) {
        var teaser = $(item).find('.GridPieceTeaser');
        var parent = $(item);
        // Checks to make sure the blue box is hidden before it animates it.  If it is in the out position then close.
        
            if (timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function () {
            if (teaser.css('left') == '10px') 
                openBox(parent, teaser, pieceSize, isRightMostItem);            
            }, 300)

    }).mouseleave(function (e) {
        if (timer) {
            clearTimeout(timer);
            timer = null
        }
        timer = setTimeout(function () {
            closeBox(pieceID, pieceSize);
        }, 300)
    });

    $(item).find('.clickItem').click(function () {
        var link = $(item).find('.gridPieceMore');
        window.location.href = link.attr('href');
    });
}


function setupItemForClick(item, pieceSize, pieceID, isRightMostItem) {
    //set the mouseover/click states of the grid pieces.
    $(item).click(function (e) {
        var teaser = $(item).find('.GridPieceTeaser');
        var parent = $(item);

        // Checks to make sure the blue box is hidden before it animates it.  If it is in the out position then close.
        if (teaser.css('left') == '10px') {
            //close any open teasers
            $('.GridPiece').each(function (e) {
                var otherTeaser = $(this).find('.GridPieceTeaser');

                if (otherTeaser.css('left') != '10px') {
                    closeBox($(this).find('input').attr('value').split('--')[0], $(this).find('input').attr('value').split('--')[1]);
                }
            });
            openBox(parent, teaser, pieceSize, isRightMostItem);
        }
        else {
            closeBox(pieceID, pieceSize);
        }
    });

    $(item).find('.clickItem').dblclick(function () {
        var link = $(item).find('.gridPieceMore');
        window.location.href = link.attr('href');
    });
}
function openBox(parent, teaser, pieceSize, isRightMostItem) {
    var leftPos;
    
    // Set the position to move the blue details box to.
    if (!isRightMostItem) {
        switch (pieceSize) {
            case 'large':
                leftPos = '+=374px';
                break;
            case 'Med':
                leftPos = '+=178px';
                break;
            default:
                leftPos = '+=178px';
                break;
        }
    }
    else {
        leftPos = '-=168px';
    }

    // move the selected grid piece to the top layer
    parent.css('z-index', '100');
    teaser.css('display', 'block');
    teaser.animate({ 'left': leftPos }, 'slow');

    if (pieceSize == 'Small') {
        var text = $(teaser).find('.GridPieceTeaserText');
        var back = $(teaser).find('.GridPieceTeaserBack');
        text.animate({ 'height': '183px' }, 'slow');
        back.animate({ 'height': '203px' }, 'slow');    
    }
}
function closeBox(boxID, pieceSize) {
    var gridPiece = $('#teaserID' + boxID)

    gridPiece.parent().parent().css('z-index', '90');
    gridPiece.animate({ 'left': '10px' }, 'fast', function () {
        gridPiece.css('display', 'none');
        gridPiece.parent().parent().css('z-index', '80');
    });

    if (pieceSize == 'Small') {
        var text = $(gridPiece).find('.GridPieceTeaserText');
        var back = $(gridPiece).find('.GridPieceTeaserBack');
        text.animate({ 'height': '80px' }, 'fast');
        back.animate({ 'height': '97px' }, 'fast');
    }

}
